advent-of-code

Entries to advent of code, multiple years
git clone git://git.finwo.net/misc/advent-of-code
Log | Files | Refs

commit 20c9963950516dc1108d5b81c37c2542ec490bc5
parent 3cab6425a0cbaf1b422e87a030660f94d27440ec
Author: finwo <finwo@pm.me>
Date:   Tue, 15 Nov 2022 15:22:38 +0100

Added 2015/02 answer

Diffstat:
A2015/day-02/index.js | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 78 insertions(+), 0 deletions(-)

diff --git a/2015/day-02/index.js b/2015/day-02/index.js @@ -0,0 +1,78 @@ +const fs = require('fs'); +const through = require('through2'); + +let total = 0; +let ribbon = 0; + +fs.createReadStream('input') + + // Convert to characters + .pipe(through(function(chunk, enc, cb) { + chunk = chunk.toString(); + for(let i = 0; i < chunk.length; i++) { + this.push(chunk.charAt(i)); + } + cb(); + })) + + // Normalize newlines + .pipe(through(function(chunk, enc, cb) { + chunk = chunk.toString(); + switch(chunk) { + case '\r': + if (this.osx) { + this.push('\n'); + } + this.osx = true; + break; + default: + if (this.osx) { + if (chunk !== '\n') { + this.push('\n'); + } + this.osx = false; + } + this.push(chunk); + break; + } + cb(); + })) + + // Convert characters to lines + .pipe(through(function(chunk, enc, cb) { + if (!this.buf) this.buf = Buffer.alloc(0); + if (chunk.toString() == '\n') { + this.push(this.buf); + this.buf = Buffer.alloc(0); + return cb(); + } + const buf = Buffer.alloc(this.buf.length + chunk.length); + this.buf.copy(buf, 0); + chunk.copy(buf, this.buf.length); + this.buf = buf; + cb(); + })) + + // Business logic + // Convert to dimensions + .pipe(through.obj(function(chunk, enc, cb) { + this.push(chunk.toString().split('x').map(c => parseInt(c))); + cb(); + })) + + // Business logic + // Convert to wrapping paper required for the package + .pipe(through.obj(function(dimensions, enc, cb) { + const w = dimensions[0], h = dimensions[1], l = dimensions[2]; + const planes = [w*h,h*l,l*w]; + const ribbons = [2*(w+h), 2*(h+l), 2*(l+w)]; + total += planes.reduce((r, a) => r + (2*a), 0); + total += Math.min(...planes); + ribbon += Math.min(...ribbons) + (w*h*l); + cb(); + })) + + .on('finish', () => { + console.log(`The elfs need ${total} sqft of wrapping paper`); + console.log(`The elfs need ${ribbon} feet of ribbon`); + })