commit 47b7fe31661ae1a6be1ed86a54b539484994e8f5
parent 36f3726b488bf16bef7c5d7fc1cc94d2145b4d46
Author: finwo <finwo@pm.me>
Date: Sun, 4 Dec 2022 20:26:11 +0100
2022/04 solution
Diffstat:
1 file changed, 58 insertions(+), 0 deletions(-)
diff --git a/2022/day-04/index.js b/2022/day-04/index.js
@@ -0,0 +1,58 @@
+const fs = require('fs');
+const through = require('through2');
+const line_for_line = require('../common/line-for-line');
+
+let enclosed = 0;
+let overlapS = 0;
+let overlapM = 0;
+
+fs.createReadStream('input')
+ .pipe(line_for_line())
+
+ // Business logic
+ .pipe(through(function(line, enc, cb) {
+ line = line.toString();
+
+ const rangeA = line.split(',').shift().split('-').map(x => parseInt(x));
+ const rangeB = line.split(',').pop().split('-').map(x => parseInt(x));
+
+ if ((rangeA[0] <= rangeB[0]) && (rangeA[1] >= rangeB[1])) {
+ // Range A encloses range B
+ enclosed++;
+ } else if ((rangeA[0] >= rangeB[0]) && (rangeA[1] <= rangeB[1])) {
+ // Range B encloses range A
+ enclosed++;
+ }
+
+ this.push(line);
+ cb();
+ }))
+
+ // Business logic
+ .pipe(through(function(line, enc, cb) {
+ line = line.toString();
+
+ const rangeA = line.split(',').shift().split('-').map(x => parseInt(x));
+ const rangeB = line.split(',').pop().split('-').map(x => parseInt(x));
+
+ // Thanks to https://stackoverflow.com/a/64745177
+ // Took me longer to figure out the brainfart than I'm willing to admit
+ let overlapSO = Math.max(rangeA[0], rangeB[0]) <= Math.min(rangeA[1], rangeB[1]);
+ let overlapMe =
+ ((rangeA[0] <= rangeB[0]) && (rangeA[1] >= rangeB[0])) || // rangeB[0] within rangeA
+ ((rangeA[0] <= rangeB[1]) && (rangeA[1] >= rangeB[1])) || // rangeB[1] within rangeA
+ ((rangeB[0] <= rangeA[0]) && (rangeB[1] >= rangeA[0])) || // rangeA[0] within rangeB
+ ((rangeB[0] <= rangeA[1]) && (rangeB[1] >= rangeA[1])) // rangeA[1] within rangeB
+ ;
+
+ if (overlapSO) overlapS++;
+ if (overlapMe) overlapM++;
+
+ cb();
+ }))
+
+ .on('finish', () => {
+ // done
+ console.log('Enclosed', enclosed);
+ console.log('Overlap', { overlapS, overlapM });
+ });