solve Day08 in Python

This commit is contained in:
WieErWill 2023-12-10 12:06:17 +01:00
parent 4ec228f14f
commit dc4dd65452
5 changed files with 104 additions and 3 deletions

View File

@ -33,3 +33,36 @@ ZZZ = (ZZZ, ZZZ)
```
Starting at AAA, follow the left/right instructions. How many steps are required to reach ZZZ?
## Part Two
The sandstorm is upon you and you aren't any closer to escaping the wasteland. You had the camel follow the instructions, but you've barely left your starting position. It's going to take significantly more steps to escape!
What if the map isn't for people - what if the map is for ghosts? Are ghosts even bound by the laws of spacetime? Only one way to find out.
After examining the maps a bit longer, your attention is drawn to a curious fact: the number of nodes with names ending in A is equal to the number ending in Z! If you were a ghost, you'd probably just start at every node that ends with A and follow all of the paths at the same time until they all simultaneously end up at nodes that end with Z.
For example:
```
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)
```
Here, there are two starting nodes, 11A and 22A (because they both end with A). As you follow each left/right instruction, use that instruction to simultaneously navigate away from both nodes you're currently on. Repeat this process until all of the nodes you're currently on end with Z. (If only some of the nodes you're on end with Z, they act like any other node and you continue as normal.) In this example, you would proceed as follows:
- Step 0: You are at 11A and 22A.
- Step 1: You choose all of the left paths, leading you to 11B and 22B.
- Step 2: You choose all of the right paths, leading you to 11Z and 22C.
- Step 3: You choose all of the left paths, leading you to 11B and 22Z.
- Step 4: You choose all of the right paths, leading you to 11Z and 22B.
- Step 5: You choose all of the left paths, leading you to 11B and 22C.
- Step 6: You choose all of the right paths, leading you to 11Z and 22Z.
So, in this example, you end up entirely on nodes that end in Z after 6 steps.
Simultaneously start on every node that ends with A. How many steps does it take before you're only on nodes that end with Z?

View File

@ -50,7 +50,7 @@ def run_test():
expected_result = 6
instructions, node_map = parse_file("../test.txt")
result = navigate_network(instructions, node_map)
assert result == expected_result, f"Test failed, expected {expected_result} but got {total_winnings}"
assert result == expected_result, f"Test failed, expected {expected_result} but got {result}"
print(f"Test passed with {result} steps.")
except AssertionError as error:
print(error)

58
Day08/python/solution2.py Normal file
View File

@ -0,0 +1,58 @@
import sys
from math import gcd
def parse_file(file_path):
print(f"Parsing file: {file_path}")
with open(file_path, 'r') as file:
D = file.read().strip()
steps, rule = D.split('\n\n')
GO = {'L': {}, 'R': {}}
for line in rule.split('\n'):
st, lr = line.split('=')
left, right = lr.split(',')
GO['L'][st.strip()] = left.strip()[1:].strip()
GO['R'][st.strip()] = right[:-1].strip()
return [0 if char == 'L' else 1 for char in steps], GO
def lcm(xs):
ans = 1
for x in xs:
ans = (x * ans) // gcd(x, ans)
return ans
def navigate_network_simultaneously(steps, GO):
print("Starting navigation of network.")
POS = [s for s in GO['L'] if s.endswith('A')]
T = {}
t = 0
while True:
NP = []
for i, p in enumerate(POS):
p = GO['L' if steps[t % len(steps)] == 0 else 'R'][p]
if p.endswith('Z'):
T[i] = t + 1
if len(T) == len(POS):
print(f"All paths reached 'Z' nodes at step {t + 1}.")
return lcm(T.values())
NP.append(p)
POS = NP
t += 1
print(f"Step {t}: Current nodes - {POS}")
assert False
def run_test():
print("Running test...")
expected_result = 6
steps, GO = parse_file("../test2.txt")
result = navigate_network_simultaneously(steps, GO)
assert result == expected_result, f"Test failed, expected {expected_result} but got {result}"
print(f"Test passed with {result} steps.")
def main():
run_test()
steps, GO = parse_file("../input.txt")
result = navigate_network_simultaneously(steps, GO)
print(f"All paths reached 'Z' nodes simultaneously in {result} steps.")
if __name__ == "__main__":
main()

10
Day08/test2.txt Normal file
View File

@ -0,0 +1,10 @@
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)

View File

@ -39,7 +39,7 @@ I aim to complete each day's puzzle on the same day, but as with any challenge,
| 05 | ✅ | ✅ | [Day05 README](/Day05/README.md) |
| 06 | ✅ | ✅ | [Day06 README](/Day06/README.md) |
| 07 | ✅ | ✅ | [Day07 README](/Day07/README.md) |
| 08 | ✅ | | [Day08 README](/Day08/README.md) |
| 08 | ✅ | | [Day08 README](/Day08/README.md) |
| 09 | ❓ | ❓ | [Day09 README](/Day09/README.md) |
| 10 | ❓ | ❓ | [Day10 README](/Day10/README.md) |
| 11 | ❓ | ❓ | [Day11 README](/Day11/README.md) |