Published
Edited
Nov 19, 2019
1 fork
7 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
world0 = new Set([[13,9],[14,9],[15,9],[14,10],[13,11],[15,11]].map(rep))
Insert cell
Insert cell
rep = (xy) => xy.join(',')
Insert cell
Insert cell
derep = str => str.split(',').map(Number)
Insert cell
Insert cell
alive = (cell,world) => world.has(rep(cell))
Insert cell
Insert cell
new Set([[1,2]]).has([1,2])
Insert cell
Insert cell
Insert cell
Insert cell
function draw(w) {
return html`
<svg width=${width} height=${width/nx*ny}>
${[...w].map(derep).map(makeRect)}
</svg>`
}
Insert cell
Insert cell
function makeRect(cell) {
const [x,y] = cell;
const cellsize=width/nx;
return svg`<rect x=${cellsize*x} y=${cellsize*y} height=${cellsize} width=${cellsize} fill="red"/>`
}
Insert cell
Insert cell
draw(world0)
Insert cell
Insert cell
Insert cell
function neighbors(cell) {
const [cx,cy] = cell;
const all = [-1,0,1].flatMap(x => [-1,0,1].map(y => [cx+x,cy+y]));
return all.filter(n => rep(n) !== rep(cell));
}
Insert cell
Insert cell
function alive_next(cell,w) {
const live_neighbors = neighbors(cell).filter(n => alive(n,w)).length
if (!alive(cell,w))
return live_neighbors === 3;
else
return live_neighbors >=2 && live_neighbors <= 3;
}
Insert cell
Insert cell
alive_next([14,9],world0)
Insert cell
Insert cell
function evolve(world) {
const all = range(nx).flatMap(x => range(ny).map(y => [x,y]));
return new Set(all.filter(cell=>alive_next(cell,world)).map(rep));
}
Insert cell
Insert cell
draw(evolve(world0))
Insert cell
Insert cell
world = {
let c = world0;
while (true) {
await Promises.delay(1000);
c = evolve(c)
yield c;
}
}
Insert cell
Insert cell
Insert cell
draw(world)
Insert cell
Insert cell
Insert cell
Insert cell
range = n => [...new Array(n).keys()]
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