Published
Edited
Dec 12, 2020
1 fork
4 stars
Insert cell
Insert cell
Insert cell
function* run(fn = tick) {
const seen = new Set()
let occupied = new Set()
let key = print(occupied)
while (!seen.has(key)) {
seen.add(key)
occupied = fn(occupied)
key = print(occupied)
yield occupied
}
}
Insert cell
output = vl.markSquare({ size: 15 })
.encode(
vl.x().fieldQ('0').scale({ nice: false }),
vl.y().fieldQ('1').scale({ nice: false }),
)
Insert cell
grid = input.trim().split('\n').map(s => s.split(''))
Insert cell
seats = {
const seats = new Set()
for (let i = 0; i < grid.length; i++)
for (let j = 0; j < grid[i].length; j++)
if (grid[i][j] === 'L')
seats.add(String([i, j]))
return seats
}
Insert cell
function* neighbors(seat) {
const [x, y] = seat.split(',').map(Number)
for (const dx of [-1, 0, 1])
for (const dy of [-1, 0, 1])
if (!(dx === 0 && dy === 0))
yield [x + dx, y + dy]
}
Insert cell
function tick(occupied) {
const next = new Set(occupied)

const counts = {}
for (const seat of occupied) {
for (const neighbor of neighbors(seat))
counts[neighbor] = (counts[neighbor] || 0) + 1
}
for (const seat of seats) {
const neighbors = counts[seat] || 0
if (!occupied.has(seat) && neighbors === 0) {
next.add(seat)
} else if (occupied.has(seat) && neighbors >= 4) {
next.delete(seat)
}
}
return next
}
Insert cell
part1 = {
await visibility()
for (const occupied of run())
yield occupied.size
}
Insert cell
function tick2(occupied) {
const next = new Set(occupied)

const counts = {}
for (const seat of occupied) {
const [x0, y0] = seat.split(',').map(Number)
for (const [dx, dy] of directions()) {
let p = [x0, y0]
do {
p[0] += dx
p[1] += dy
if (seats.has(String(p))) {
counts[p] = (counts[p] || 0) + 1
break
}
} while (p[0] >= 0 && p[0] < grid.length && p[1] >= 0 && p[1] < grid[0].length)
}
}
for (const seat of seats) {
const neighbors = counts[seat] || 0
if (!occupied.has(seat) && neighbors === 0) {
next.add(seat)
} else if (occupied.has(seat) && neighbors >= 5) {
next.delete(seat)
}
}
return next
}
Insert cell
part2 = {
await visibility()
for (const occupied of run(tick2))
yield occupied.size
}
Insert cell
function* directions() {
for (const dx of [-1, 0, 1])
for (const dy of [-1, 0, 1])
if (!(dx === 0 && dy === 0))
yield [dx, dy]
}
Insert cell
function print(occupied) {
const out = grid.map(l => l.slice())
for (const seat of occupied) {
const [x, y] = seat.split(',').map(Number)
out[x][y] = '#'
}
return out.map(l => l.join('')).join('\n')
}
Insert cell
Insert cell
Insert cell
import { vl } from '@vega/vega-lite-api'
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