Published
Edited
Jan 2, 2020
Insert cell
Insert cell
Insert cell
function partition(array, n) {
return array.length!=0 ? [array.splice(0, n)].concat(partition(array, n)) : []; // stolen from stackoverflow
}
Insert cell
intoLayers = input => partition(input.split("").slice().map(Number), 25 * 6) // 1d to 2d array by index
Insert cell
solve1 = input =>
Object.values(
intoLayers(input) // into layers of 25 x 6 pixels
.map(layer => ({values: layer, numzeros: layer.reduce((acc,inc) => inc == 0 ? acc + 1 : acc)})) // count 0s
.reduce((acc, inc) => inc.numzeros < acc.numzeros ? inc : acc) // layer with fewest 0s
.values // layer
.reduce((acc, inc) => inc == 1 ? ({ones: acc.ones + 1, twos: acc.twos}) :
inc == 2 ? ({ones: acc.ones, twos: acc.twos + 1}) : acc, ({ones: 0, twos: 0})) // count 1s and 2s
)
.reduce((acc,inc) => acc * inc) // multiply counts
Insert cell
solve1(data)
Insert cell
Insert cell
intoPixels = input => {
const layers = intoLayers(input) // into pixel layers
let image = []
for(let j = 0; j < 25 * 6; j++) {
let pixel = 2
for(let i = 0; i < layers.length; i++) if(pixel==2) pixel = layers[i][j] // overwrite transparent pixels
image.push(pixel)
}
return partition(image, 25)
.map((row,y) => row.map((col,x) => ({x: x, y: y, value: col}))) // add x and y coords to each for plotting
}
Insert cell
solve2 = input => {
const svg = d3.select(DOM.svg(25,6))
.style("width", "100%")
.style("height", "auto")
svg.append("g").selectAll("g")
.data(intoPixels(input))
.enter().append("g").selectAll("rect")
.data(d => d).enter().append("rect")
.attr("x", d => d.x)
.attr("y", d => d.y)
.attr("width", 1)
.attr("height", 1)
.style("fill", d => [d3.hcl(0,0,0), d3.hcl(0,0,100), d3.hcl(50,0,50)][d.value])
.style("shape-rendering", "crispEdges")
return svg.node()
}
Insert cell
solve2(data)
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