DEV Community

Discussion on: Advent of Code 2019 Solution Megathread - Day 8: Space Image Format

Collapse
 
maxart2501 profile image
Massimo Artizzu • Edited

Aw yeah something simple again! Maybe even a little bit too simple? 😄

Anyway, in JavaScript:

const WIDTH = 25;
const HEIGHT = 6;
const layerSize = WIDTH * HEIGHT;

const layers = input.match(new RegExp(`[012]{${layerSize}}`, 'g'));

// Part One
function count(string, needle) {
  return string.split(needle).length - 1;
}
const digitCounts = [0, 1, 2].map(digit => layers.map(layer => count(layer, digit)));
const minZeros = Math.min(...digitCounts[0]);
const minZeroLayerIndex = digitCounts[0].indexOf(minZeros);

console.log(digitCounts[1][minZeroLayerIndex] * digitCounts[2][minZeroLayerIndex]);

// Part Two
const composed = Array.from({ length: layerSize }, (_, index) => {
  return layers.find(layer => layer[index] !== '2')[index];
});

// Pretty print the output ðŸĪŠ
console.log(
  composed.join('')
    .replace(/0/g, ' ').replace(/1/g, '#')
    .match(new RegExp(`[012]{${WIDTH}}`, 'g'))
    .join('\n')
);

Check my repo for my input.

By the way, here's the language count for day 7 (it could be subject to change as it was a kind of complex challenge):

JavaScript × 3
Python × 2
C × 1
Clojure × 1
Java × 1
Swift × 1