advent-of-code

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

index.js (2010B)


      1 const fs           = require('fs');
      2 const through      = require('through2');
      3 const line_by_line = require('../common/line-for-line');
      4 
      5 const buf1 = [];
      6 
      7 // CAUTION: mixes in-place
      8 function mix(idx, buf) {
      9   const len = buf.length;
     10   const lem = len - 1;
     11   for(let i=0; i<len; i++) {
     12     const j = idx[i];                 // Fetch current location
     13     const v = buf.splice(j, 1).pop(); // Extract current value
     14     let   m = v % lem;                // Calculate move equivalent (
     15     while(m<0) m += lem;
     16 
     17     // Recalculate location for everything after j
     18     for(let x=0; x<len; x++) if (idx[x] > j) idx[x]--;
     19 
     20     // Calculate new location
     21     let n = (((j+v)%lem)+lem)%lem;
     22 
     23     // Recalculate location for everything after n
     24     for(let x=0; x<len; x++) if (idx[x] >= n) idx[x]++;
     25 
     26     idx[i] = n;          // Store new location
     27     buf.splice(n, 0, v); // Store value at new location
     28   }
     29 }
     30 
     31 // fs.createReadStream('sample')
     32 fs.createReadStream('input')
     33   .pipe(line_by_line())
     34 
     35   // Minor parsing
     36   .pipe(through.obj(function(line, enc, cb) {
     37     line = line.toString();
     38     buf1.push(parseInt(line));
     39     cb();
     40   }))
     41 
     42   .on('finish', () => {
     43     console.log('loaded');
     44 
     45     // Build index tracking list
     46     const len  = buf1.length;
     47     let   idx1 = new Array(len).fill().map((_,i)=>i);
     48     let   idx2 = new Array(len).fill().map((_,i)=>i);
     49     let   buf2 = buf1.map(v => v * 811589153);
     50 
     51     // process.stdout.write(`Init 1:\n${buf1.join(', ')}\n\n`);
     52     // process.stdout.write(`Init 2:\n${buf2.join(', ')}\n\n`);
     53 
     54     // Mix everything up
     55     mix(idx1, buf1);
     56     for(let i=1; i<=10; i++) {
     57       mix(idx2, buf2);
     58       // process.stdout.write(`After ${i} round(s) of mixing:\n${buf2.join(', ')}\n${idx2.join(', ')}\n\n`);
     59     }
     60 
     61     let z1 = buf1.indexOf(0);
     62     let z2 = buf2.indexOf(0);
     63 
     64     const step1 = buf1[(z1+1000)%len] + buf1[(z1+2000)%len] + buf1[(z1+3000)%len];
     65     const step2 = buf2[(z2+1000)%len] + buf2[(z2+2000)%len] + buf2[(z2+3000)%len];
     66 
     67     console.log({ step1, step2 });
     68   });