advent-of-code

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

commit 91c9b62b74133b2f30c75bb3ee41198bfa15b785
parent 95b832f24de507987174f78e95e8e7f59658c912
Author: finwo <finwo@pm.me>
Date:   Tue, 20 Dec 2022 23:05:21 +0100

2022/20 solution

Diffstat:
A2022/day-20/index.js | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A2022/day-20/sample | 7+++++++
2 files changed, 75 insertions(+), 0 deletions(-)

diff --git a/2022/day-20/index.js b/2022/day-20/index.js @@ -0,0 +1,68 @@ +const fs = require('fs'); +const through = require('through2'); +const line_by_line = require('../common/line-for-line'); + +const buf1 = []; + +// CAUTION: mixes in-place +function mix(idx, buf) { + const len = buf.length; + const lem = len - 1; + for(let i=0; i<len; i++) { + const j = idx[i]; // Fetch current location + const v = buf.splice(j, 1).pop(); // Extract current value + let m = v % lem; // Calculate move equivalent ( + while(m<0) m += lem; + + // Recalculate location for everything after j + for(let x=0; x<len; x++) if (idx[x] > j) idx[x]--; + + // Calculate new location + let n = (((j+v)%lem)+lem)%lem; + + // Recalculate location for everything after n + for(let x=0; x<len; x++) if (idx[x] >= n) idx[x]++; + + idx[i] = n; // Store new location + buf.splice(n, 0, v); // Store value at new location + } +} + +// fs.createReadStream('sample') +fs.createReadStream('input') + .pipe(line_by_line()) + + // Minor parsing + .pipe(through.obj(function(line, enc, cb) { + line = line.toString(); + buf1.push(parseInt(line)); + cb(); + })) + + .on('finish', () => { + console.log('loaded'); + + // Build index tracking list + const len = buf1.length; + let idx1 = new Array(len).fill().map((_,i)=>i); + let idx2 = new Array(len).fill().map((_,i)=>i); + let buf2 = buf1.map(v => v * 811589153); + + // process.stdout.write(`Init 1:\n${buf1.join(', ')}\n\n`); + // process.stdout.write(`Init 2:\n${buf2.join(', ')}\n\n`); + + // Mix everything up + mix(idx1, buf1); + for(let i=1; i<=10; i++) { + mix(idx2, buf2); + // process.stdout.write(`After ${i} round(s) of mixing:\n${buf2.join(', ')}\n${idx2.join(', ')}\n\n`); + } + + let z1 = buf1.indexOf(0); + let z2 = buf2.indexOf(0); + + const step1 = buf1[(z1+1000)%len] + buf1[(z1+2000)%len] + buf1[(z1+3000)%len]; + const step2 = buf2[(z2+1000)%len] + buf2[(z2+2000)%len] + buf2[(z2+3000)%len]; + + console.log({ step1, step2 }); + }); diff --git a/2022/day-20/sample b/2022/day-20/sample @@ -0,0 +1,7 @@ +1 +2 +-3 +3 +-2 +0 +4