Open andreiz opened 10 months ago
Seems like a straightforward binary tree traversal, repeating the instructions on a cycle and counting the steps.
First thing we need is a function to parse the input into a data structure. I chose to keep it simple use a dictionary maping from one node to the left and right nodes it's connected to, representing the graph. A couple of typealias
es for readability.
Traversal is pretty trivial. Initialize current node to "AAA", then loop the instructions continuously until we reach "ZZZ".
Parsing and calling is trivial too.
Part 2. Now we have a set of start nodes (all the ones ending in "A") and end nodes (ending in "Z"). We go from all the start nodes simultaneously until all paths reach end nodes. If only some of paths reach end, they act like any other node and we continue as normal.
The trick part here is that in order for all the paths to finish at the same time (lengh) some of them will have to be repeated several times until other paths catch up (paths have different periodicities). But we don't actually need to repeat them. We calculate path for each start node, then compute the least common multiple of all the path lengths, giving us the one encompassing path length.
traverseGraph
now has a parameter for starting node and an updated stopping condition and also returns the path length.
And then we just find all starting nodes, get path length for each one, and calculate least common multiple of them.
https://adventofcode.com/2023/day/8
Input: https://adventofcode.com/2023/day/8/input