commit 36f3726b488bf16bef7c5d7fc1cc94d2145b4d46
parent 958abb797bc364dd7ce30ad02cd6d3742bf79143
Author: finwo <finwo@pm.me>
Date: Sun, 4 Dec 2022 19:44:24 +0100
2022/03 solution
Diffstat:
| A | 2022/day-03/index.js | | | 93 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 93 insertions(+), 0 deletions(-)
diff --git a/2022/day-03/index.js b/2022/day-03/index.js
@@ -0,0 +1,93 @@
+const fs = require('fs');
+const through = require('through2');
+const line_for_line = require('../common/line-for-line');
+
+let priority = 0;
+let priorityGroup = 0;
+
+let startA = 'a'.charCodeAt(0);
+let stopA = 'z'.charCodeAt(0);
+let startB = 'A'.charCodeAt(0);
+let stopB = 'Z'.charCodeAt(0);
+
+fs.createReadStream('input')
+ .pipe(line_for_line())
+
+ // Business logic
+ .pipe(through(function(line, enc, cb) {
+ line = line.toString();
+
+ const compartmentA = line.substr(0, line.length / 2);
+ const compartmentB = line.substr(line.length / 2);
+
+ for(let i=0; i<compartmentA.length; i++) {
+ const c = compartmentA.substr(i, 1);
+ const C = c.charCodeAt(0);
+ if (!~compartmentB.indexOf(c)) continue;
+
+ // console.log(`FOUND ${c} in ${compartmentA} and ${compartmentB}`);
+ if (startA <= C && C <= stopA) {
+ priority += 1 + C - startA;
+ } else if (startB <= C && C <= stopB) {
+ priority += 27 + C - startB;
+ }
+
+ break;
+ }
+
+ cb();
+ }))
+
+ .on('finish', () => {
+ // done
+ console.log('Priority', priority);
+ });
+
+let groupBuffer = [];
+fs.createReadStream('input')
+ .pipe(line_for_line())
+
+ // Group by 3
+ .pipe(through(function(line, enc, cb) {
+ line = line.toString();
+ groupBuffer.push(line);
+ if (groupBuffer.length == 3) {
+ this.push(JSON.stringify(groupBuffer));
+ groupBuffer = [];
+ }
+ cb();
+ }))
+
+ // Business logic
+ .pipe(through(function(line, enc, cb) {
+ const [x,y,z] = JSON.parse(line);
+ // Find the badge
+
+ // Iterate the one, as it must have the badge
+ for(let i=0; i<x.length; i++) {
+
+ // Filter down to the badge
+ const c = x.substr(i, 1);
+ const C = c.charCodeAt(0);
+ if (!~y.indexOf(c)) continue;
+ if (!~z.indexOf(c)) continue;
+
+ // console.log(`FOUND ${c} in group [${x}, ${y}, ${z}]`);
+ if (startA <= C && C <= stopA) {
+ priorityGroup += 1 + C - startA;
+ } else if (startB <= C && C <= stopB) {
+ priorityGroup += 27 + C - startB;
+ }
+
+ break;
+ }
+
+ // console.log(JSON.parse(line));
+ cb();
+ }))
+
+
+ .on('finish', () => {
+ // done
+ console.log('PriorityGroup', priorityGroup);
+ })