Skip to content

Commit c9ad7d1

Browse files
committed
Add day 21
1 parent fe8b3eb commit c9ad7d1

File tree

5 files changed

+49
-0
lines changed

5 files changed

+49
-0
lines changed

2021/21/21.jl

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
function part1(p1, p2, dice=100, goal=1000)
2+
s1, s2 = 0, 0
3+
die_value, rolls = 0, 0
4+
die() = rolls += 1; mod1(die_value += 1, dice)
5+
roll() = die() + die() + die()
6+
while s1 < goal || s2 < goal
7+
s1 += (p1 = mod1(p1 + roll(), 10))
8+
s1 >= goal && break
9+
s2 += (p2 = mod1(p2 + roll(), 10))
10+
end
11+
return min(s1, s2) * rolls
12+
end
13+
14+
function part2(P1, P2, goal=22) # Add 1 to goal, since julia is 1 indexed, so dp lookup is different
15+
dp = zeros(Int64, (goal+11, goal+11, 10, 10, 2))
16+
dp[1, 1, P1, P2, 1] = 1
17+
dice = [sum(1 for a=1:3, b=1:3, c=1:3 if a+b+c==s) for s=3:9]
18+
for s1=1:goal-1, s2=1:goal-1
19+
for d1=1:10, d2=1:10, add=3:9
20+
d1a = mod1(d1+add, 10)
21+
dp[s1+d1a, s2, d1a, d2, 2] += dp[s1, s2, d1, d2, 1] * dice[add-2]
22+
d2a = mod1(d2+add, 10)
23+
dp[s1, s2+d2a, d1, d2a, 1] += dp[s1, s2, d1, d2, 2] * dice[add-2]
24+
end
25+
end
26+
dps = sum(dp, dims=(3, 4, 5))
27+
S1, S2 = 0, 0
28+
for s1=1:goal+11, s2=1:goal+11
29+
if max(s1, s2) >= goal
30+
s1 > s2 ? S1 += dps[s1, s2, 1, 1, 1] : S2 += dps[s1, s2, 1, 1, 1]
31+
end
32+
end
33+
return max(S1, S2)
34+
end
35+
36+
function main()
37+
p1, p2 = parse.(Int, getindex.(split.(readlines(), ": "), 2))
38+
println(part1(p1, p2))
39+
println(part2(p1, p2))
40+
end
41+
main()

2021/21/example.ans

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
739785
2+
444356092776315

2021/21/example.in

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Player 1 starting position: 4
2+
Player 2 starting position: 8

2021/21/input.ans

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
675024
2+
570239341223618

2021/21/input.in

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Player 1 starting position: 7
2+
Player 2 starting position: 4

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy