Skip to content

Commit

Permalink
feat(js): add solutions for 2023 day 8
Browse files Browse the repository at this point in the history
  • Loading branch information
timkurvers committed Dec 9, 2023
1 parent 04873d6 commit 55e035f
Show file tree
Hide file tree
Showing 3 changed files with 817 additions and 0 deletions.
67 changes: 67 additions & 0 deletions js/src/2023/08/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { Graph, lcm, solution } from '../../utils';

const PATH_MATCHER = /(\w+) = \((\w+), (\w+)\)/g;

const parse = (input) => {
const parts = input.trim().split('\n\n');

const instructions = parts[0].split('').map((i) => (i === 'L' ? 0 : 1));

const network = new Graph();
for (const [_, from, a, b] of parts[1].matchAll(PATH_MATCHER)) {
network.edge(from, a);
network.edge(from, b);
}

return { instructions, network };
};

export const partOne = solution((input) => {
const { network, instructions } = parse(input);

const start = network.find('AAA');
const goal = network.find('ZZZ');

let current = start;
let steps = 0;
while (current !== goal) {
const move = instructions[steps % instructions.length];
const next = current.edges[move] || current.edges[0];
current = next.to;
++steps;
}

return steps;
});

export const partTwo = solution((input) => {
const { network, instructions } = parse(input);

const starts = network.vertices.filter((v) => v.value.endsWith('A'));
const atGoal = (ghost) => ghost.current.value.endsWith('Z');
const hasCycle = (ghost) => ghost.cycle && ghost.cycle.length;

const ghosts = starts.map((start) => ({
current: start,
cycle: null,
}));
let steps = 0;
while (!ghosts.every(hasCycle)) {
const move = instructions[steps % instructions.length];
for (const ghost of ghosts) {
const next = ghost.current.edges[move] || ghost.current.edges[0];
ghost.current = next.to;
if (atGoal(ghost)) {
if (!ghost.cycle) {
ghost.cycle = { start: steps };
} else if (!ghost.cycle.length) {
ghost.cycle.length = steps - ghost.cycle.start;
}
}
}
++steps;
}

// We meet again AoC 2022 day 11! :o
return lcm(ghosts.map((ghost) => ghost.cycle.length));
});
34 changes: 34 additions & 0 deletions puzzles/2023/08/examples.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
part-one:
- input: |
RL
AAA = (BBB, CCC)
BBB = (DDD, EEE)
CCC = (ZZZ, GGG)
DDD = (DDD, DDD)
EEE = (EEE, EEE)
GGG = (GGG, GGG)
ZZZ = (ZZZ, ZZZ)
answer: 2
- input: |
LLR
AAA = (BBB, BBB)
BBB = (AAA, ZZZ)
ZZZ = (ZZZ, ZZZ)
answer: 6
part-two:
- input: |
LR
11A = (11B, XXX)
11B = (XXX, 11Z)
11Z = (11B, XXX)
22A = (22B, XXX)
22B = (22C, 22C)
22C = (22Z, 22Z)
22Z = (22B, 22B)
XXX = (XXX, XXX)
answer: 6
Loading

0 comments on commit 55e035f

Please sign in to comment.