+/AoC

advent of code

git clone https://git.julia.blue/+/AoC

Julia RyanDay 253ce0ac6

master
1.3 KiB42 linesraw
1from functools import cache
2
3with open("input") as f:
4    codes = f.read().splitlines()
5pad = lambda s: {
6    c: (x, y) for y, line in enumerate(s.splitlines()) for x, c in enumerate(line)
7}
8numpad = pad("789\n456\n123\n.0A")
9dirpad = pad(".^A\n<v>")
10diff = lambda a, b: (b[0] - a[0], b[1] - a[1])
11strip_num = lambda s: int("".join((c for c in s if c.isdigit())))
12
13
14@cache
15def shortest(s, target, level=-1):
16    if level == target:
17        return len(s)
18    cur = numpad["A"] if level < 0 else dirpad["A"]
19    total = 0
20    for c in s:
21        dx, dy = diff(cur, new := numpad[c] if level < 0 else dirpad[c])
22        hori = ("<" if dx < 0 else ">") * abs(dx)
23        vert = ("^" if dy < 0 else "v") * abs(dy)
24        recurse = lambda s: shortest(s + "A", target, level + 1)
25        a, b = recurse(hori + vert), recurse(vert + hori)
26        # fmt: off
27        if    (level <  0 and cur[0] == 0 and new[1] == 3
28            or level >= 0 and cur[0] == 0 and new[1] == 0):
29            total += a
30        elif  (level <  0 and cur[1] == 3 and new[0] == 0
31            or level >= 0 and cur[1] == 0 and new[0] == 0):
32            total += b
33        # fmt: on
34        else:
35            total += min(a, b)
36        cur = new
37    return total
38
39
40solve = lambda n: sum((shortest(code, n) * strip_num(code) for code in codes))
41print(solve(2))
42print(solve(25))