adventofcode-2021/day21/part2.lua

47 lines
1.7 KiB
Lua
Raw Normal View History

2021-12-21 13:01:48 +01:00
#!/usr/bin/env luajit
require("utils")
local f = io.open(arg[3])
local fst = tonumber(string.match(f:read("*l"), "Player 1 starting position: (.*)")) - 1
local snd = tonumber(string.match(f:read("*l"), "Player 2 starting position: (.*)")) - 1
f:close()
local function index(score1, score2, loc1, loc2)
2021-12-21 14:13:58 +01:00
return loc2 + 10 * (loc1 + 31 * (score2 + 31 * score1))
2021-12-21 13:01:48 +01:00
end
local function deindex(index)
local lo2, loc1, score2, score1
loc2, index = index % 10, math.floor(index / 10)
2021-12-21 14:13:58 +01:00
loc1, index = index % 31, math.floor(index / 31)
score2, index = index % 31, math.floor(index / 31)
2021-12-21 13:01:48 +01:00
score1 = index
return score1, score2, loc1, loc2
end
local poss = { [index(0, 0, fst, snd)] = 1 }
local size = 1
local c1, c2 = 0, 0
while size > 0 do
local newposs = {}
size = 0
for i, c in pairs(poss) do
local s1, s2, l1, l2 = deindex(i)
if s2 >= 21 then
c2 = c2 + c
else
2021-12-21 14:13:58 +01:00
local i3 = index(s2, s1 + (l1 + 3) % 10 + 1, l2, (l1 + 3) % 10); newposs[i3] = (newposs[i3] or 0) + 1 * c
local i4 = index(s2, s1 + (l1 + 4) % 10 + 1, l2, (l1 + 4) % 10); newposs[i4] = (newposs[i4] or 0) + 3 * c
local i5 = index(s2, s1 + (l1 + 5) % 10 + 1, l2, (l1 + 5) % 10); newposs[i5] = (newposs[i5] or 0) + 6 * c
local i6 = index(s2, s1 + (l1 + 6) % 10 + 1, l2, (l1 + 6) % 10); newposs[i6] = (newposs[i6] or 0) + 7 * c
local i7 = index(s2, s1 + (l1 + 7) % 10 + 1, l2, (l1 + 7) % 10); newposs[i7] = (newposs[i7] or 0) + 6 * c
local i8 = index(s2, s1 + (l1 + 8) % 10 + 1, l2, (l1 + 8) % 10); newposs[i8] = (newposs[i8] or 0) + 3 * c
local i9 = index(s2, s1 + (l1 + 9) % 10 + 1, l2, (l1 + 9) % 10); newposs[i9] = (newposs[i9] or 0) + 1 * c
2021-12-21 13:01:48 +01:00
size = size + 27 * c
end
end
poss = newposs
c1, c2 = c2, c1
end
2021-12-21 14:13:58 +01:00
io.write(string.format("max(%d %d) = %d\n", c1, c2, math.max(c1, c2)))