DEV Community

Cover image for Advent of Code 2023 - December 8th
Rob van der Leek
Rob van der Leek

Posted on

Advent of Code 2023 - December 8th

In this series, I'll share my progress with the 2023 version of Advent of Code.

Check the first post for a short intro to this series.

You can also follow my progress on GitHub.

December 8th

The puzzle of day 8 was not so hard. I like graph problems, although this was pretty basic.

My pitfall for this puzzle: I have no clue how to find the number that's a common factor for all path lengths. Something similar to Greatest Common Divisor, but what 🀷. In the end a brute force approach worked and doesn't take that long on my M1 laptop.

Solution here, do not click if you want to solve the puzzle first yourself
#!/usr/bin/env python3
import math

with open('input.txt') as infile:
    lines = infile.readlines()
directions = [d for d in lines[0].strip()]

graph = {}
for line in lines[2:]:
    parts = line.strip().split(' = ')
    targets = parts[1][1:-1].split(', ')
    graph[parts[0]] = {'L': targets[0], 'R': targets[1]}

dir_idx = 0
steps = 0
nodes = [n for n in graph.keys() if n.endswith('A')]
finished = []
while len([n for n in nodes if not n.endswith('Z')]) > 0:
    steps += 1
    for idx, n in enumerate(nodes):
        if idx in [f[0] for f in finished]:
            continue
        nodes[idx] = graph[n][directions[dir_idx]]
        if nodes[idx].endswith('Z'):
            finished.append((idx, steps))
    if dir_idx < len(directions) - 1:
        dir_idx += 1
    else:
        dir_idx = 0
for f in finished:
    print(f'Finished node {f[0]} in {f[1]} steps')

highest = max([f[1] for f in finished])
total = highest
while True:
    all_divisors = True
    for f in finished:
        if total % f[1] != 0:
            all_divisors = False
    if all_divisors:
        break
    else:
        total += highest
print(total)
Enter fullscreen mode Exit fullscreen mode

That's it! See you again tomorrow!

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay