Published
Edited
Nov 13, 2019
Insert cell
Insert cell
Insert cell
(part2.iterations*part2.offsets.length)+_.sum(part2.offsets)
Insert cell
part2 = {
let state = initial
// const result = []
console.time('part2')
const iterations = 500
// for (let i = 0; i < 50000000000; i++) {
for (let i = 0; i < iterations; i++) {
// result.push(print(state))
// yield(state)
state = tick(state)
}
// return result
let sum = 0
const offsets = []
for (let k of state.keys()) {
offsets.push(k - iterations)
sum += k
}
// console.timeEnd('part2')
return { offsets, sum, iterations }
// return state
// return sum
}
Insert cell
part1 = {
let state = initial
const result = []
for (let i = 0; i < 20; i++) {
result.push(print(state))
state = tick(state)
}
// return result
let sum = 0
for (let k of state.keys())
sum += k
return sum
}
Insert cell
print(initial)
Insert cell
print(tick(initial))
Insert cell
function print(state) {
let r = ''
for (let i = -10; i < 40; i++) {
r += state.has(i) ? '#' : '.'
}
return r
}
Insert cell
function tick(state) {
const nextState = new Set()
for (let k of state) {
for (let i = k - 2; i <= k + 2; i++) {
// each rule
for (let pattern of rules) {
let match = true
for (let j = 0; j < pattern.length; j++) {
if ((state.has(i + j - 2) ? '#' : '.') !== pattern[j]) {
match = false
break
}
}
if (match) {
nextState.add(i)
break
}
}
}
}
return nextState
}
Insert cell
rules = lines.slice(1).map(s => s.split(' => '))
.filter(([pattern, result]) => result === '#')
.map(([pattern, result]) => {
return pattern.split('')
})
Insert cell
initial = _.reduce(lines[0].split(' ')[2].split(''), (set, value, key) => {
if (value === '#')
set.add(key)
return set
}, new Set())
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more