+/AoC

advent of code

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

Joseph RyanA lot closer this year! (missing 19 and 22b)0579d0a

master
1.5 KiB57 linesraw
1from itertools import count
2from operator import add
3from collections import defaultdict
4
5
6def size(elves):
7    return (
8        (min(x for x, _ in elves), min(y for _, y in elves)),
9        (max(x for x, _ in elves), max(y for _, y in elves)),
10    )
11
12
13def show(elves):
14    (x0, y0), (x1, y1) = size(elves)
15    for y in range(y0, y1 + 1):
16        for x in range(x0, x1 + 1):
17            print("#" if (x, y) in elves else ".", end="")
18        print()
19    print()
20
21
22elves = set()
23neighbors = tuple((x, y) for y in range(-1, 2) for x in range(-1, 2) if x or y)
24dirs = ((0, -1), (0, 1), (-1, 0), (1, 0))
25checks = (((-1, 0), (0, 0), (1, 0)), ((0, -1), (0, 0), (0, 1)))
26for y, line in enumerate(open("input")):
27    for x, c in enumerate(line):
28        if c == "#":
29            elves.add((x, y))
30# show(elves)
31
32dir = 0
33for i in count(1):
34    moves = defaultdict(list)
35    moved = False
36    for e in elves:
37        if not any(tuple(map(add, e, n)) in elves for n in neighbors):
38            continue
39        for j in range(4):
40            pos = tuple(map(add, e, dirs[(dir + j) % 4]))
41            if not any(
42                tuple(map(add, pos, c)) in elves for c in checks[(dir + j) % 4 // 2]
43            ):
44                moves[pos].append(e)
45                break
46    for k, v in moves.items():
47        if len(v) == 1:
48            moved = True
49            elves.remove(v[0])
50            elves.add(k)
51    dir += 1
52    if i == 10:
53        (x0, y0), (x1, y1) = size(elves)
54        print((y1 - y0 + 1) * (x1 - x0 + 1) - len(elves))
55    if not moved:
56        print(i)
57        break