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(); }
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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