Skip to content

Instantly share code, notes, and snippets.

@cloudrac3r
Created December 8, 2019 05:25
Show Gist options
  • Save cloudrac3r/c6b3c708230ebb3014b093c06535931d to your computer and use it in GitHub Desktop.
Save cloudrac3r/c6b3c708230ebb3014b093c06535931d to your computer and use it in GitHub Desktop.
Advent of Code 2019 day 8 solution (both parts)
const {read} = require("../util/read")
class SpaceImage {
constructor(width, height) {
this.width = width
this.height = height
this.layers = []
}
importPixels(pixels) {
const pixelsPerLayer = this.width * this.height
const layerCount = pixels.length / pixelsPerLayer
this.layers = Array(layerCount).fill(undefined).map((_, i) => pixels.slice(pixelsPerLayer*i, pixelsPerLayer*(i+1)))
return this
}
checksum() {
let layer = this.layers.sort((a, b) => (a.reduce((a, c) => a + (c === 0), 0) - b.reduce((a, c) => a + (c === 0), 0)))[0]
console.log(layer)
return layer.reduce((a, c) => a + (c === 1), 0) * layer.reduce((a, c) => a + (c === 2), 0)
}
renderVisible() {
let rendered = null
for (let i = this.layers.length-1; i >= 0; i--) {
const layer = this.layers[i]
if (rendered === null) {
rendered = layer.slice()
} else {
for (let j = 0; j < layer.length; j++) {
if (layer[j] !== 2) rendered[j] = layer[j]
}
}
}
return rendered
}
renderArt() {
const rendered = this.renderVisible()
let result = ""
for (let y = 0; y < this.height; y++) {
for (let x = 0; x < this.width; x++) {
result += " .?"[rendered[x + this.width*y]]
}
result += "\n"
}
return result
}
}
function loadImage(file) {
const lines = read(file).asLines()
const width = +lines[0]
const height = +lines[1]
const pixels = [...lines[2]].map(x => +x)
return new SpaceImage(width, height).importPixels(pixels)
}
function checksumFile(file) {
return loadImage(file).checksum()
}
function renderFile(file) {
return loadImage(file).renderArt()
}
module.exports.checksumFile = checksumFile
module.exports.renderFile = renderFile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment