Skip to content

Instantly share code, notes, and snippets.

@gnarf
Last active December 21, 2021 09:34
Show Gist options
  • Save gnarf/deb7dee6942b14ad8035805667c6a679 to your computer and use it in GitHub Desktop.
Save gnarf/deb7dee6942b14ad8035805667c6a679 to your computer and use it in GitHub Desktop.
#AdventOfCode 2021 Day 21
I=(await(await fetch("https://adventofcode.com/2021/day/21/input")).text(w=W=0)).match(/(\d+)/g)
u=(c,...a)=>{for(let i in U=[,,,1,3,6,7,6,3,1])U[i]&&((r,c,p,P,s=0,S=0,t)=>(((s+=p=((p-1+r)%10)+1)>20)&&(t?W+=c:w+=c),s<21&&u(c,P,p,S,s,!t)))(+i,U[i]*c,...a)}
u(1,I[1],I[3])
w>W?w:W
players=[{position:4,score:0},{position:8, score:0}];
(await(await fetch("https://adventofcode.com/2021/day/21/input")).text(players=[])).replace(/(\d+)\n/g,(_,position)=>players.push({position,score:0}))
dierolls = 0
playerturn = 0
rolldie=()=>((dierolls++)%100)+1
while(players.every(p=>p.score<1000))
{
player=players[playerturn]
spaces = rolldie() + rolldie() + rolldie();
player.position = ((player.position-1 + spaces)%10)+1
player.score += player.position
playerturn = +(!playerturn)
}
players[playerturn].score * dierolls
players=[{position:4,score:0},{position:8, score:0}];
// (await(await fetch("https://adventofcode.com/2021/day/21/input")).text(players=[])).replace(/(\d+)\n/g,(_,position)=>players.push({position,score:0}))
rollcounts = [,,,1,3,6,7,6,3,1]
p1wins=p2wins=0
playturn=(p1pos, p1score, p2pos, p2score, playerturn, roll, count) => {
// console.log('Playing turn', p1pos,p1score,p2pos,p2score,playerturn,roll,count);
if (playerturn) {
p2pos = ((p2pos-1+roll)%10)+1
if ((p2score += p2pos)>20)
{
// console.log('p2wins', count)
return p2wins += count
}
} else {
p1pos = ((p1pos-1+roll)%10)+1
if ((p1score += p1pos)>20)
{
// console.log('p1wins', count)
return p1wins += count
}
}
for(index in rollcounts)if (rollcounts[index])
playturn(p1pos, p1score, p2pos, p2score, +(!playerturn), +index, count*rollcounts[index])
}
for(index in rollcounts)if (rollcounts[index]) playturn(players[0].position, 0, players[1].position, 0, 0, +index, rollcounts[index]);
Math.max(p1wins,p2wins)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment