advent_of_code/2023/8/8_2.py

56 lines
1.5 KiB
Python
Raw Normal View History

2023-12-20 01:31:58 +01:00
#!/usr/bin/env python
# 2023 - Advent Of Code 8 - part 2
from math import lcm
from functools import reduce
#file = 'input_example2.txt'
file = 'input.txt'
# pylint: disable=consider-using-with
input_lines = [line.strip('\n') for line in open(file, encoding="utf-8")]
directions = input_lines[0]
print(directions)
nodes = {}
for l in input_lines[2:]:
k, v = l.split(' = ')
nodes[k] = v[1:-1].split(', ')
cur_nodes = [x for x in nodes if x.endswith('A')]
print(cur_nodes)
allz = False
count = 0
ends_num = [0] * len(cur_nodes)
while not allz:
ends = [False] * len(cur_nodes)
for current, _ in enumerate(cur_nodes):
# print(cur_node)
if directions[count % len(directions)] == 'L':
cur_nodes[current] = nodes[cur_nodes[current]][0]
elif directions[count % len(directions)] == 'R':
cur_nodes[current] = nodes[cur_nodes[current]][1]
# check z
if cur_nodes[current].endswith('Z'):
ends[current] = True
ends_num[current] = count
print(f'end {cur_nodes[current]} found at {count} for {current} {ends}')
allz = False not in ends
if True in ends:
# print(f'end found at {count} {ends}')
print(f'ends list: {ends_num}')
if 0 not in ends_num:
break
count += 1
print()
print(f'count: {count} {ends}')
print(f'{ends_num}')
ends_num2 = [x + 1 for x in ends_num]
print(f'reduced: {reduce(lcm, ends_num)}')
print(f'reduced: {reduce(lcm, ends_num2)}')