advent-of-code

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

commit 4c9bdcf38343377bccb21899cc5460fea5c37b34
parent acd93d720bf1b0d151fdbcee5e3a51db53e1680f
Author: finwo <finwo@pm.me>
Date:   Wed,  8 Dec 2021 17:22:41 +0100

Finished puzzle 2 of day-00

Diffstat:
Asrc/day-01/puzzle-02.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 58 insertions(+), 0 deletions(-)

diff --git a/src/day-01/puzzle-02.ts b/src/day-01/puzzle-02.ts @@ -0,0 +1,58 @@ +import readline from 'readline'; +import fs from 'fs'; +import events from 'events'; + +let history = []; +let sumLast = null; +let increasedTotal = 0; + +let texts = [ + 'decreased', + 'no change', + 'increased', +]; + +function sum(...n) { + return n.reduce((r,a)=>r+a, 0); +} + +(async () => { + + const rl = readline.createInterface({ + input : fs.createReadStream(__dirname + '/input-01'), + output : null, + }); + + rl.on('line', line => { + if ((!line) || isNaN(line)) return; + const depth = parseInt(line); + history.push(depth); + + while (history.length >= 3) { + const sumCurrent = sum(...history.slice(0,3)); + history.shift(); + + if (null === sumLast) { + process.stdout.write(`${sumCurrent} (N/A - no previous measurement)\n`); + } else { + const increased = (sumCurrent > sumLast) | 0; + const decreased = (sumCurrent < sumLast) | 0; + increasedTotal += increased; + process.stdout.write(`${sumCurrent} (${texts[1 + increased - decreased]})\n`); + } + + sumLast = sumCurrent; + } + + }); + + await events.once(rl, 'close'); + + process.stdout.write('\n\n'); + process.stdout.write('---[ REPORT ]---\n'); + process.stdout.write(`Increased ${increasedTotal} times\n`); + process.stdout.write('\n'); + + +})(); +