generated from alvesvaren/AoC-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
22.py
59 lines (47 loc) · 1.78 KB
/
22.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Something with this is broken, got my answer correct by using the 100% broken code (didn't work on example) and just adding +1
import aoc
from collections import deque
from itertools import chain, islice
p1, p2 = aoc.get_input(22).split("\n\n")
def parse_deck(data: str) -> deque:
new_data = data.split("\n")[1:]
return deque(map(int, new_data[::-1]))
deck1 = parse_deck(p1)
deck2 = parse_deck(p2)
orig_deck1, orig_deck2 = deck1.copy(), deck2.copy()
def play_game_recursive(deck1: deque, deck2: deque, mem: set=set()) -> tuple[int, deque, deque]:
while len(deck1) != 0 and len(deck2) != 0:
decks_as_tuples = tuple(deck1), tuple(deck2)
if decks_as_tuples in mem:
return (1, deck1, deck2)
mem.add(decks_as_tuples)
card1 = deck1.pop()
card2 = deck2.pop()
if len(deck1) >= card1 and len(deck2) >= card2:
winner = play_game_recursive(
deque(list(islice(deck1, card1+1))[:1]),
deque(list(islice(deck2, card2+1))[:1]), mem)
if winner[0] == 1:
deck1.appendleft(card1)
deck1.appendleft(card2)
elif winner[0] == 2:
deck2.appendleft(card2)
deck2.appendleft(card1)
continue
if card1 > card2:
deck1.appendleft(card1)
deck1.appendleft(card2)
else:
deck2.appendleft(card2)
deck2.appendleft(card1)
if len(deck2) == 0:
return (1, deck1, deck2)
if len(deck1) == 0:
return (2, deck1, deck2)
raise ValueError("Invalid input")
result, deck1, deck2 = play_game_recursive(deck1, deck2)
print(deck1, deck2)
sum1 = 0
for i,thing in enumerate(chain(deck1, deck2)):
sum1 += thing*(i+1)
print(sum1)