Published
Edited
Aug 1, 2019
Insert cell
Insert cell
Insert cell
Insert cell
function makeGrid (cols, rows) {
let grid = []
for (let y = 0; y < rows; y++) {
grid[y] = []
for (let x = 0; x < cols; x++) {
grid[y][x] = Math.random() > 0.5 ? 1 : 0
}
}
return grid
}
Insert cell
Insert cell
Insert cell
function getValidNeighbors (x, y) {
const neighbors = [
[ x + 1, y ],
[ x - 1, y ],
[ x, y + 1 ],
[ x, y - 1 ]
]
return neighbors.filter( ([nx, ny]) =>
nx >= 0 && nx < cols && ny >= 0 && ny < rows
)
}
Insert cell
// recursive function to get neighbors of a point, and get their neighbors ...
// NOTE: normally, I wouldn't pass grid to this function, but it's a hack to circumvent how Observable updates "global" notebook variables
function walk ([x, y], grid, polygon = []) {
const neighbors = getValidNeighbors(x, y)

neighbors.forEach( ([nx, ny]) => {
if (!grid[ny][nx]) {
return
}
grid[ny][nx] = 0
polygon.push([nx, ny])
walk([nx, ny], grid, polygon)
})
// make sure to add the point to the polygon!
return [ [x, y], ...polygon ]
}
Insert cell
function march (grid) {
const polygons = []

for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
if (!grid[y][x]) {
continue
}
grid[y][x] = 0
const polygon = walk([x, y], grid)
if (polygon.length) {
polygons.push(polygon)
}
}
}
return polygons
}
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