Here’s my solution to Day Two of Advent of Code.
Part 1
const testInput = `Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green`;
const maxCubes = { red: 12, green: 13, blue: 14 };
function isCubeValid(cube) {
for (let [color, currentMax] of Object.entries(maxCubes)) {
if (cube.includes(color)) {
const value = Number(cube.replace(color, "").trim());
if (value > currentMax) return false;
}
}
return true;
}
function isLineValid(line) {
return line
.split(":")[1]
.trim()
.replace(/;/g, ",")
.split(",")
.map(cube => cube.trim())
.every(isCubeValid);
}
const total = input => {
return input
.split("\n")
.map(line => isLineValid(line))
.reduce((acc, curr, index) => {
if (curr) {
return acc + index + 1;
}
return acc;
}, 0);
};
console.log(total(testInput)); // 8
Part 2
const testInput = `Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green`;
function parseLine(line) {
const cubes = line
.split(":")[1]
.trim()
.replace(/;/g, ",")
.split(",")
.map(cube => cube.trim());
return cubes;
}
function getMinCubes(line) {
let cubesCount = { red: 0, green: 0, blue: 0 };
const cubes = parseLine(line);
cubes.forEach(cube => {
for (let [color, _] of Object.entries(maxCubes)) {
if (cube.includes(color)) {
const value = Number(cube.replace(color, "").trim());
if (value > cubesCount[color]) {
cubesCount[color] = value;
}
}
}
});
return cubesCount;
}
const total = input => {
return input
.split("\n")
.map(line => getMinCubes(line))
.map(cubes => {
return Object.values(cubes).reduce((acc, curr) => acc * curr, 1);
})
.reduce((acc, curr) => acc + curr, 0);
};
console.log(total(testInput)); //2286
Hopefully more tomorrow, if I can get to it.