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


      1 const fs            = require('fs');
      2 const through       = require('through2');
      3 const line_for_line = require('../common/line-for-line');
      4 
      5 let enclosed = 0;
      6 let overlapS  = 0;
      7 let overlapM  = 0;
      8 
      9 fs.createReadStream('input')
     10   .pipe(line_for_line())
     11 
     12   // Business logic
     13   .pipe(through(function(line, enc, cb) {
     14     line = line.toString();
     15 
     16     const rangeA = line.split(',').shift().split('-').map(x => parseInt(x));
     17     const rangeB = line.split(',').pop().split('-').map(x => parseInt(x));
     18 
     19     if ((rangeA[0] <= rangeB[0]) && (rangeA[1] >= rangeB[1])) {
     20       // Range A encloses range B
     21       enclosed++;
     22     } else if ((rangeA[0] >= rangeB[0]) && (rangeA[1] <= rangeB[1])) {
     23       // Range B encloses range A
     24       enclosed++;
     25     }
     26 
     27     this.push(line);
     28     cb();
     29   }))
     30 
     31   // Business logic
     32   .pipe(through(function(line, enc, cb) {
     33     line = line.toString();
     34 
     35     const rangeA = line.split(',').shift().split('-').map(x => parseInt(x));
     36     const rangeB = line.split(',').pop().split('-').map(x => parseInt(x));
     37 
     38     // Thanks to https://stackoverflow.com/a/64745177
     39     // Took me longer to figure out the brainfart than I'm willing to admit
     40     let overlapSO = Math.max(rangeA[0], rangeB[0]) <= Math.min(rangeA[1], rangeB[1]);
     41     let overlapMe = 
     42       ((rangeA[0] <= rangeB[0]) && (rangeA[1] >= rangeB[0])) || // rangeB[0] within rangeA
     43       ((rangeA[0] <= rangeB[1]) && (rangeA[1] >= rangeB[1])) || // rangeB[1] within rangeA
     44       ((rangeB[0] <= rangeA[0]) && (rangeB[1] >= rangeA[0])) || // rangeA[0] within rangeB
     45       ((rangeB[0] <= rangeA[1]) && (rangeB[1] >= rangeA[1]))    // rangeA[1] within rangeB
     46     ;
     47 
     48     if (overlapSO) overlapS++;
     49     if (overlapMe) overlapM++;
     50 
     51     cb();
     52   }))
     53 
     54   .on('finish', () => {
     55     // done
     56     console.log('Enclosed', enclosed);
     57     console.log('Overlap', { overlapS, overlapM });
     58   });