aoc2021/21.jl

71 lines
1.4 KiB
Julia

function make_dice(max_value)
next = max_value - 1
r = 0
function roll()
r += 1
next += 1
next %= max_value
return next + 1
end
function rolls()
r
end
roll, rolls
end
function advance(pos, dice)
pos += dice()+dice()+dice()
((pos - 1) % 10) + 1
end
function solution21_1()
pos_a = 8
pos_b = 5
dice, times = make_dice(100)
score_a = 0
score_b = 0
while true
pos_a = advance(pos_a, dice)
score_a += pos_a
println("a -> $pos_a ($score_a)")
if score_a >= 1000
r = times()
println("$score_b $r $(score_b * r)")
break
end
pos_b = advance(pos_b, dice)
score_b += pos_b
println("b -> $pos_b ($score_b)")
if score_b >= 1000
r = times()
println("$score_a $r $(score_a * r)")
break
end
end
end
using Pkg
Pkg.add("Memoize")
using Memoize
DICE = [(a,b,c) for a in 1:3 for b in 1:3 for c in 1:3]
@memoize function round(pa, pb, sa, sb)
sum(map(DICE) do dice
npa = pa + sum(dice)
npa = ((npa - 1) % 10) + 1
nsa = sa + npa
if nsa >= 21
[1, 0]
else
circshift(round(pb, npa, sb, nsa), 1)
end
end)
end
function solution21_2()
round(8, 5, 0, 0)
end
solution21_2()