aboutsummaryrefslogtreecommitdiff
path: root/2023/08/solve.py
blob: 957cee191db4286add0a54baa8b3cbcb1b20be97 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
L = [l.strip() for l in open("input").readlines()]

path = L[0]
nodes = dict(
    (p := n.split(" = ")) and (p[0], p[1][1:-1].split(", ")) for n in L[2:]
)


def part1(start):
    steps = 0
    curr = start
    while True:
        d = path[steps % len(path)]
        curr = nodes[curr][0 if d == "L" else 1]
        steps += 1
        if curr[2] == "Z":
            return steps


def lcm(steps):
    bi_gcd = lambda m, n: m if not n else bi_gcd(n, m % n)
    res = steps[0]
    for s in steps[1:]:
        res = s * (res // bi_gcd(res, s))
    return res


def part2():
    steps = []
    curr = [k for k in nodes.keys() if k[2] == "A"]
    for s in curr:
        steps.append(part1(s))

    # modulo ring yay
    return lcm(steps)


print(part1("AAA"))
print(part2())