Skip to content

Commit 1e66606

Browse files
committed
Day 15
1 parent 2eeff6a commit 1e66606

File tree

2 files changed

+70
-6
lines changed

2 files changed

+70
-6
lines changed

year2020/aoc15.py

+27-4
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,38 @@
11
# https://adventofcode.com/2020/day/15
22

3+
from collections import defaultdict
4+
from collections.abc import Generator
5+
from itertools import islice
6+
37
from helpers import read_puzzle
48

9+
PART_1 = 2020
10+
PART_2 = 30000000
11+
12+
13+
def parse(s: str) -> tuple[int, ...]:
14+
return tuple(int(x) for x in s.split(','))
15+
16+
17+
def gen_memory_game(start_nums: tuple[int, ...]) -> Generator[int]:
18+
last_seen: defaultdict[int, int | None] = defaultdict(lambda: None)
19+
turn, n = 0, 0
20+
for turn, n in enumerate(start_nums, start=1):
21+
last_seen[n] = turn
22+
yield n
23+
while True:
24+
prev, last_seen[n] = last_seen[n], turn
25+
yield (n := 0 if prev is None else turn - prev)
26+
turn += 1
27+
528

6-
def parse(s: str) -> list[int]:
7-
return [int(line) for line in s.split()]
29+
def get_nth_num(start_nums: tuple[int, ...], n: int) -> int:
30+
return next(islice(gen_memory_game(start_nums), n - 1, None))
831

932

1033
def solve() -> tuple[int, int]:
11-
_puzzle = parse(read_puzzle())
12-
return 0, 0
34+
start_nums = parse(read_puzzle())
35+
return get_nth_num(start_nums, PART_1), get_nth_num(start_nums, PART_2)
1336

1437

1538
if __name__ == '__main__':

year2020/tests/test_aoc15.py

+43-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,46 @@
1-
from year2020.aoc15 import solve
1+
from itertools import islice
2+
3+
import pytest
4+
5+
from year2020.aoc15 import PART_1, PART_2, gen_memory_game, get_nth_num, solve
6+
7+
8+
def test_gen_memory_game():
9+
first_10 = tuple(islice(gen_memory_game((0, 3, 6)), 10))
10+
assert first_10 == (0, 3, 6, 0, 3, 3, 1, 0, 4, 0)
11+
12+
13+
@pytest.mark.parametrize(
14+
'start_nums, result',
15+
(
16+
((0, 3, 6), 436),
17+
((1, 3, 2), 1),
18+
((2, 1, 3), 10),
19+
((1, 2, 3), 27),
20+
((2, 3, 1), 78),
21+
((3, 2, 1), 438),
22+
((3, 1, 2), 1836),
23+
),
24+
)
25+
def test_get_2020th_num(start_nums, result):
26+
assert get_nth_num(start_nums, PART_1) == result
27+
28+
29+
@pytest.mark.parametrize(
30+
'start_nums, result',
31+
(
32+
((0, 3, 6), 175594),
33+
((1, 3, 2), 2578),
34+
((2, 1, 3), 3544142),
35+
((1, 2, 3), 261214),
36+
((2, 3, 1), 6895259),
37+
((3, 2, 1), 18),
38+
((3, 1, 2), 362),
39+
),
40+
)
41+
def test_get_30000000th_num(start_nums, result):
42+
assert get_nth_num(start_nums, PART_2) == result
243

344

445
def test_solve():
5-
assert solve() == (0, 0)
46+
assert solve() == (700, 51358)

0 commit comments

Comments
 (0)