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


      1 const fs = require('fs');
      2 const through = require('through2');
      3 const line_for_line = require('../common/line-for-line');
      4 
      5 // Fully expecting other operations later, otherwise would've just kept a single counter
      6 let score_1 = 0;
      7 let score_2 = 0;
      8 
      9 const choices = [
     10   {
     11     name   : 'rock',
     12     opp    : 'A',
     13     me     : 'X',
     14     points : 1,
     15     map    : 0,
     16     Z      : 6 + 2,
     17     Y      : 3 + 1,
     18     X      : 0 + 3,
     19   },
     20   {
     21     name   : 'paper',
     22     opp    : 'B',
     23     me     : 'Y',
     24     points : 2,
     25     map    : 1,
     26     Z      : 6 + 3,
     27     Y      : 3 + 2,
     28     X      : 0 + 1,
     29   },
     30   {
     31     name   : 'scissors',
     32     opp    : 'C',
     33     me     : 'Z',
     34     points : 3,
     35     map    : 2,
     36     Z      : 6 + 1,
     37     Y      : 3 + 3,
     38     X      : 0 + 2,
     39   },
     40 ];
     41 
     42 fs.createReadStream('input')
     43   .pipe(line_for_line())
     44 
     45   // Business logic
     46   .pipe(through(function(line, enc, cb) {
     47     line = line.toString();
     48 
     49     const [c_them, c_me] = line.split(' ');
     50     const them = choices.find(choice => choice.opp == c_them);
     51     const me   = choices.find(choice => choice.me  == c_me  );
     52 
     53     // Step 1, run the match
     54     const match = them.map - me.map;
     55     let   result = '';
     56     switch(match) {
     57       case -1:
     58       case  2:
     59         score_1 += 6 + me.points;
     60         result = 'win';
     61         break;
     62       case 0:
     63         score_1 += 3 + me.points;
     64         result = 'draw';
     65         break;
     66       case 1:
     67       case -2:
     68         score_1 += 0 + me.points;
     69         result = 'lose';
     70         break;
     71       default:
     72         throw new Error(`other: ${match}`);
     73         break;
     74     }
     75 
     76     // Step 2. chosen winner
     77 
     78     score_2 += them[c_me];
     79 
     80     console.log({ them, me, match, result });
     81     cb();
     82   }))
     83 
     84   .on('finish', () => {
     85     // done
     86     console.log('Step 1:', score_1);
     87     console.log('Step 2:', score_2);
     88   })