advent_of_code/2023/day8/main.py

105 lines
2.5 KiB
Python

import re
from tracemalloc import start
import numpy as np
import graphviz
def get_answer(graph, keys, inst):
inst_idx = 0
steps = 0
current_keys = keys
while True:
all_ending_in_z = True
for i in range(len(current_keys)):
current_keys[i] = graph[current_keys[i]][inst[inst_idx]]
if all_ending_in_z and (current_keys[i][2] != 'Z'):
all_ending_in_z = False
steps += 1
inst_idx = (inst_idx + 1)%len(inst)
if all_ending_in_z:
return steps
def visualize_graph(graph):
dot = graphviz.Digraph(comment='Advent of Code Day 8')
for i in graph:
for key in graph[i].keys():
dot.node(i)
dot.edge(i, graph[i][key])
dot.render('day8.dot')
f = open('input.txt', 'r')
my_graph = dict(dict())
content = f.read()
lines = content.splitlines()
instructions = []
starting_keys = []
ending_keys = []
for line_count, line in enumerate(lines):
last_repeat = False
if line_count == 0:
instructions = line
else:
numbers = re.findall(r'[A-Za-z]+', line)
if len(numbers) == 3:
if numbers[0][2] == 'A':
starting_keys.append(numbers[0])
my_graph[numbers[0]] = {"L": numbers[1], "R": numbers[2]}
counters = [0]*len(starting_keys)
inst_idx = 0
steps = 0
# current_keys = starting_keys
# while True:
# all_ending_in_z = True
# for i in range(len(current_keys)):
# current_keys[i] = my_graph[current_keys[i]][instructions[inst_idx]]
# if all_ending_in_z and (current_keys[i][2] != 'Z'):
# all_ending_in_z = False
# steps += 1
# inst_idx = (inst_idx + 1)%len(instructions)
# if all_ending_in_z:
# return steps
starting_key = 'AAA'
ending_key = 'ZZZ'
inst_idx = 0
list_steps = []
for key in starting_keys:
steps = 0
current_key = key
loop = True
while loop:
current_key = my_graph[current_key][instructions[inst_idx]]
inst_idx = (inst_idx + 1)%len(instructions)
if (current_key[2] == 'Z'):
loop = False
steps += 1
print(steps)
list_steps.append(steps)
# print(starting_keys)
# ans = get_answer(my_graph, starting_keys, instructions)
# print(ans)
visualize_graph(my_graph)
lcm = 1#np.lcm(list_steps[0], list_steps[1])
print(lcm)
for i in range(len(list_steps)):
lcm = np.lcm(lcm, list_steps[i])
print(lcm)
print(list_steps[i]/len(instructions))
f.close()