Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 1966f13

Browse filesBrowse files
committed
day 22
1 parent f1ae4bd commit 1966f13
Copy full SHA for 1966f13

File tree

2 files changed

+58
-1
lines changed
Filter options

2 files changed

+58
-1
lines changed

‎README.md

Copy file name to clipboardExpand all lines: README.md
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
|[19](https://adventofcode.com/2020/day/19)|Monster Messages|[py](/day19/main.py), [alt](/day19/alt.py)|
2424
|[20](https://adventofcode.com/2020/day/20)|Jurassic Jigsaw|[py](/day20/main.py)|
2525
|[21](https://adventofcode.com/2020/day/21)|Allergen Assessment|[py](/day21/main.py)|
26-
|[22](https://adventofcode.com/2020/day/22)|-|-|
26+
|[22](https://adventofcode.com/2020/day/22)|Crab Combat|[py](/day22/main.py)|
2727
|[23](https://adventofcode.com/2020/day/23)|-|-|
2828
|[24](https://adventofcode.com/2020/day/24)|-|-|
2929
|[25](https://adventofcode.com/2020/day/25)|-|-|

‎day22/main.py

Copy file name to clipboard
+57Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
2+
with open("input.txt") as f:
3+
chunks = f.read().split("\n\n")
4+
5+
orig_p1 = list(map(int, chunks[0].strip().split("\n")[1:]))
6+
orig_p2 = list(map(int, chunks[1].strip().split("\n")[1:]))
7+
8+
p1 = orig_p1.copy()
9+
p2 = orig_p2.copy()
10+
11+
while len(p1) > 0 and len(p2) > 0:
12+
a, b = p1.pop(0), p2.pop(0)
13+
if a > b:
14+
p1 += [a,b]
15+
else:
16+
p2 += [b,a]
17+
18+
if len(p1) > 0:
19+
winner = p1
20+
else:
21+
winner = p2
22+
23+
print(sum(e*(len(winner)-i) for i, e in enumerate(winner)))
24+
25+
# Part 2
26+
def play_game(p1, p2):
27+
seen1, seen2 = set(), set()
28+
29+
while len(p1) > 0 and len(p2) > 0:
30+
s1 = ",".join([str(c) for c in p1])
31+
s2 = ",".join([str(c) for c in p2])
32+
if s1 in seen1 or s2 in seen2:
33+
return "p1", p1
34+
seen1.add(s1)
35+
seen2.add(s2)
36+
37+
a, b = p1.pop(0), p2.pop(0)
38+
if a <= len(p1) and b <= len(p2):
39+
winner, _ = play_game(p1.copy()[:a], p2.copy()[:b])
40+
else:
41+
if a > b:
42+
winner = "p1"
43+
else:
44+
winner = "p2"
45+
46+
if winner == "p1":
47+
p1 += [a,b]
48+
else:
49+
p2 += [b,a]
50+
51+
if len(p1) > 0:
52+
return "p1", p1
53+
else:
54+
return "p2", p2
55+
56+
_, w = play_game(orig_p1.copy(), orig_p2.copy())
57+
print(sum(e*(len(w)-i) for i, e in enumerate(w)))

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.