Public
Edited
Dec 21, 2021
1 star
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.split("\n").map((l) => Number(l.split(" ")[4]));
}
Insert cell
Insert cell
Insert cell
function playGame1(pos1, pos2) {
let p1 = { pos: pos1, score: 0 };
let p2 = { pos: pos2, score: 0 };
let die = 1;

const play = (p) => {
p.pos = ((p.pos + 3 * die + 2) % 10) + 1;
p.score += p.pos;
die += 3;
return p.score;
};

AOC.repeatWhile(() => play(p1) < 1000 && play(p2) < 1000);

return p1.score < p2.score ? p1.score * (die - 1) : p2.score * (die - 1);
}
Insert cell
function part1(input) {
return playGame1(...parse(input));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
dicePaths = [
[3, 1],
[4, 3],
[5, 6],
[6, 7],
[7, 6],
[8, 3],
[9, 1]
]
Insert cell
Insert cell
function playGame2(pos1, pos2) {
let p1Wins = 0;
let p2Wins = 0;

const play = (pos1, score1, pos2, score2, paths, isPlayer1) => {
if (score1 >= 21) {
p1Wins += paths;
return;
}
if (score2 >= 21) {
p2Wins += paths;
return;
}

for (const [dice, nPaths] of dicePaths) {
if (isPlayer1) {
const newPos = ((pos1 + dice - 1) % 10) + 1;
play(newPos, score1 + newPos, pos2, score2, paths * nPaths, !isPlayer1);
} else {
const newPos = ((pos2 + dice - 1) % 10) + 1;
play(pos1, score1, newPos, score2 + newPos, paths * nPaths, !isPlayer1);
}
}
};

play(pos1, 0, pos2, 0, 1, true);

return Math.max(p1Wins, p2Wins);
}
Insert cell
function part2(input) {
return playGame2(...parse(input));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more