commit 5797c6eea85391813f589527390d5f0d3d6d29d9
parent d66837d90c21187010e86d67bbe762d26cc88293
Author: finwo <finwo@pm.me>
Date: Sat, 10 Dec 2022 16:06:30 +0100
2022/09 solution
Diffstat:
| A | 2022/day-09/index.js | | | 78 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 78 insertions(+), 0 deletions(-)
diff --git a/2022/day-09/index.js b/2022/day-09/index.js
@@ -0,0 +1,78 @@
+const fs = require('fs');
+const through = require('through2');
+const line_for_line = require('../common/line-for-line');
+
+const x = 0;
+const y = 1;
+const head = 0;
+const pos = Array(10).fill(0).map(() => [0,0]);
+const tail = pos.length - 1;
+
+const movements = {
+ U: [0,1],
+ D: [0,-1],
+ L: [-1,0],
+ R: [1,0],
+};
+
+const follows = [
+ [[-1, -1],[-1,-1],[ 0,-1],[ 1, -1],[ 1, -1]],
+ [[-1, -1],[ 0, 0],[ 0, 0],[ 0, 0],[ 1, -1]],
+ [[-1, 0],[ 0, 0],[ 0, 0],[ 0, 0],[ 1, 0]],
+ [[-1, 1],[ 0, 0],[ 0, 0],[ 0, 0],[ 1, 1]],
+ [[-1, 1],[-1, 1],[ 0, 1],[ 1, 1],[ 1, 1]],
+];
+
+const visited = [[0,0]];
+
+fs.createReadStream('input')
+// fs.createReadStream('input')
+ .pipe(line_for_line())
+
+ // Load grid
+ .pipe(through(function(line, enc, cb) {
+ line = line.toString();
+
+ const [ aDir, aCnt ] = line.split(' ');
+ const iCnt = parseInt(aCnt);
+
+ // Build head movement reference
+ const mv = movements[aDir];
+
+ // Run N steps
+ for(let i=0; i<iCnt; i++) {
+
+ // Move head
+ pos[head][x] += mv[x];
+ pos[head][y] += mv[y];
+
+ // Iterate over segments for follow movement
+ for(let i=head+1; i<pos.length; i++) {
+ const diff = [ pos[i-1][x] - pos[i][x], pos[i-1][y] - pos[i][y] ];
+ const follow = follows[diff[y]+2][diff[x]+2];
+ pos[i][x] += follow[x];
+ pos[i][y] += follow[y];
+ }
+
+ // Track position visited
+ visited.push(
+ visited.find((p) => p[x] == pos[tail][x] && p[y] == pos[tail][y]) || [...pos[tail]]
+ );
+
+ }
+
+ cb();
+ }))
+
+ .on('finish', () => {
+
+ // So visited, so we can make it unique
+ let unique = 0;
+ visited.forEach((p,i) => {
+ if (visited.indexOf(p) == i) unique++;
+ });
+
+ console.log({ unique });
+
+ console.log('finish');
+ });