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!

The Fastest, Most Accurate API for Voice AI

Ad Image

Building an AI Agent that needs to deliver human-like conversations? | Speechmatics’ real-time ASR is available in 50 languages and can understand speech in a fraction of a second.

Try Free

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay