advent-of-code/2023/python/day08.py
Tyrel Souza 0c856bcc7e
part 1
2023-12-08 09:58:49 -05:00

99 lines
2.3 KiB
Python

import shared
from scanf import scanf
def check(d):
return all(x[-1] == "Z" for x in d.values())
# @shared.profile
def part2(rows):
MAP = {}
instructions = rows.pop(0)
rows.pop(0)
instructions = instructions.replace("L", "0")
instructions = instructions.replace("R", "1")
instructions = [int(x) for x in instructions]
print(instructions)
for row in rows:
entry, left, right = scanf("%s = (%s, %s)", row)
MAP[entry] = [left,right]
starting_entries = []
ending_entries = []
for key in MAP.keys():
if key[-1] == "A":
starting_entries.append(key)
if key[-1] == "Z":
ending_entries.append(key)
endpoints = {k: k for k in starting_entries}
print(endpoints)
print(check(endpoints))
print(starting_entries)
print()
count = 0
while True:
print(count, endpoints, check(endpoints))
for start in starting_entries:
v = endpoints[start]
idx = count % len(instructions)
l_r = instructions[idx]
_next = MAP[v][l_r]
endpoints[start] = _next
count += 1
if check(endpoints):
break
print(count)
# @shared.profile
def part1(rows):
MAP = {}
instructions = rows.pop(0)
rows.pop(0)
instructions = instructions.replace("L", "0")
instructions = instructions.replace("R", "1")
instructions = [int(x) for x in instructions]
for row in rows:
entry, left, right = scanf("%s = (%s, %s)", row)
MAP[entry] = [left,right]
count = 0
current = "AAA"
target = "ZZZ"
steps = []
while True:
steps.append(current)
idx = count % len(instructions)
l_r = instructions[idx]
current = MAP[current][l_r]
count += 1
if current == target:
steps.append(target)
break
print(steps)
print(count)
def main():
rows = [row for row in shared.load_rows(8)]
with shared.elapsed_timer() as elapsed:
part1(rows[:])
print("🕒", elapsed())
rows = [row for row in shared.load_rows(8, True)]
with shared.elapsed_timer() as elapsed:
part2(rows[:])
print("🕒", elapsed())
if __name__ == "__main__":
main()