DEV Community

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

Collapse
 
mellen profile image
Matt Ellen • Edited

SO much less difficult than yesterday. It took me a while to read the instructions correctly (need to sleep), but then I was away :D


function Pic(width, height, pixels)
{
    this.layers = [];
    let layerPixelCount = width * height;
    for(let pi = 0; pi < pixels.length; pi += layerPixelCount)
    {        
        let layerpixels = pixels.slice(pi, layerPixelCount+pi);
        let layer = new Layer(width, height, layerpixels)
        this.layers.push(layer);
    }
    this.width = width;
    this.height = height;
    this.pixels = pixels;
}

Pic.prototype.crc = function()
{
    let zerocount = Number.MAX_SAFE_INTEGER;
    let result = 0;
    for(let li = 0; li < this.layers.length; li++)
    {
        let layer = this.layers[li];
        let zc = layer.nCount(0);
        if(zc < zerocount)
        {
            zerocount = zc;
            let ones = layer.nCount(1);
            let twos = layer.nCount(2);
            result = ones*twos;
        }
    }
    return result;
};

Pic.prototype.render = function()
{
    let renderedLayer = new Layer(this.width, this.height, this.layers[0].pixels.slice(0, this.layers[0].pixels.length));
    for(let li = 1; li < this.layers.length; li++)
    {
        renderedLayer.replaceTransparent(this.layers[li].pixels);
    }

    console.log(renderedLayer.toString());
}

function Layer(width, height, pixels)
{
    this.width = width;
    this.height = height;
    this.pixels = pixels;
}

Layer.prototype.getRow = function(y)
{
    let start = y * this.width;
    let end = (y+1) * this.width;
    return this.pixels.slice(start, end);
};

Layer.prototype.nCount = function(n)
{
    return this.pixels.reduce((acc, p) => p === n ? (acc+1) : acc, 0);
}

Layer.prototype.replaceTransparent = function(newPixels)
{
    for(let pi = 0; pi < this.pixels.length; pi++)
    {
        if(this.pixels[pi] == 2)
        {
            this.pixels[pi] = newPixels[pi];
        }
    }
}

Layer.prototype.toString = function()
{
    let str = '';
    for(let y = 0; y < this.height; y++)
    {
        str += this.getRow(y).map(p =>
                                  {
                                      let result = '';
                                      switch(p)
                                      {
                                          case 0: result = '\u25af'; break;
                                          case 1: result = '\u25ae'; break;
                                      }
                                      return result;
                                  }).join('');
        str += '\n';
    }
    return str;
};

function day8()
{
    let pixels = document.querySelector('pre').innerHTML.trim().split('').map(s => parseInt(s));
    let pic = new Pic(25, 6, pixels);
    console.log('crc', pic.crc());
    pic.render();
}