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 (1400B)


      1 #!/usr/bin/env node
      2 
      3 const fs = require('node:fs');
      4 const modulo = 100;
      5 
      6 let position =  50;
      7 let zeroes   =   0;
      8 let passed   =   0;
      9 
     10 const lines = fs
     11   .readFileSync('input', 'utf-8')
     12   .split('\r\n').join('\n')
     13   .split('\r').join('\n')
     14   .split('\n')
     15   .map(str => str.trim())
     16   .filter(str => str)
     17 
     18 const directions = {
     19   L: (current, offset) => current - offset,
     20   R: (current, offset) => current + offset,
     21 };
     22 
     23 const mod = (n, m) => ((n%m)+m)%m;
     24 
     25 console.log(`The dial starts by pointing at ${position}`);
     26 for(const line of lines) {
     27   const direction = directions[line.slice(0,1)];
     28   const offset    = parseInt(line.slice(1), 10);
     29 
     30   let blockPass = position === 0 ? 1 : 0;
     31   position = direction(position, offset);
     32 
     33   let prepassed = passed;
     34   process.stdout.write(`The dial is rotated ${line} to point at ${mod(position, modulo)}`);
     35 
     36   while (position >= modulo) {
     37     position -= modulo;
     38     if (position > 0) passed++;
     39   }
     40 
     41   while (position < 0) {
     42     position += modulo;
     43     if (blockPass-- <= 0) {
     44       passed++;
     45     }
     46   }
     47 
     48   if (position === 0) {
     49     zeroes++;
     50   }
     51 
     52   if (prepassed != passed) {
     53     process.stdout.write(`, it points at zero ${passed - prepassed} times`);
     54   }
     55 
     56   process.stdout.write('.\n');
     57   // console.log(`The dial is rotated ${line} to point at ${position}.`);
     58 }
     59 
     60 console.log(`Stage one password: ${zeroes}`);
     61 console.log(`Stage two password: ${zeroes + passed}`);