AdventOfCode/2023/day8/part2.py

59 lines
1.1 KiB
Python
Raw Normal View History

2023-12-08 12:36:03 +01:00
#!/bin/python3
import re
import sys
from pprint import pprint
from collections import Counter
import numpy as np
2023-12-08 18:45:14 +01:00
from math import lcm
2023-12-08 12:36:03 +01:00
input_f = sys.argv[1]
def pp(x):
for i in x:
2023-12-08 16:56:35 +01:00
print(nodes[i].value,nodes[i].left,nodes[i].right)
2023-12-08 12:36:03 +01:00
d, *maps = open(input_f).read().split('\n')
2023-12-08 13:26:14 +01:00
class Node():
def __init__(self,value,left,right):
self.value = value
self.left = left
self.right = right
nodes = {}
2023-12-08 12:36:03 +01:00
for i in maps:
if i == '':
continue
2023-12-08 18:45:14 +01:00
nodes[i[:3]] = Node(i[:3],i[7:10],i[12:15])
2023-12-08 12:36:03 +01:00
2023-12-08 13:26:14 +01:00
current = 'AAA'
steps = 0
2023-12-08 15:24:12 +01:00
count = 0
2023-12-08 18:45:14 +01:00
while current != 'ZZZ':
steps += 1
current = nodes[current].left if d[count%len(d)] == 'L' else nodes[current].right
count += 1
print('Part 1: ',end='')
print(steps)
2023-12-08 16:56:35 +01:00
2023-12-08 15:24:12 +01:00
2023-12-08 16:56:35 +01:00
current = []
2023-12-08 15:24:12 +01:00
for i in nodes:
if i.endswith('A'):
2023-12-08 16:56:35 +01:00
current.append(i)
count = 0
steps = 0
2023-12-08 18:45:14 +01:00
total_s = []
for i in current:
count = 0
steps = 0
while not i.endswith('Z'):
steps += 1
i = nodes[i].left if d[count%len(d)] == 'L' else nodes[i].right
2023-12-08 16:56:35 +01:00
count += 1
2023-12-08 18:45:14 +01:00
total_s.append(steps)
print("Part 2: ",end='')
print(lcm(*total_s))