Solution for Advent of Code (AoC) 2023 Day 2: Cube Conundrum in JavaScript:
import fs from "fs";
import { log } from "console";
const lines = fs.readFileSync("./day2.txt", { encoding: "utf-8" }).split("\n");
function part1() {
const maxDict = {
red: 12,
green: 13,
blue: 14,
};
let sum = 0;
let gameId = 1;
for (const line of lines) {
let passes = true;
const sets = line.replace(/Game [\d]*:\s/g, "").split(";");
for (const set of sets) {
const colorWithCount = set.split(",");
for (const colorCount of colorWithCount) {
const [count, color] = colorCount.trim().split(" ");
if (count > maxDict[color]) {
passes = false;
}
}
}
if (passes) {
sum += gameId;
}
gameId++;
}
log(sum);
}
function part2() {
let sum = 0;
for (const line of lines) {
const sets = line.replace(/Game [\d]*:\s/g, "").split(";");
const gameMaxMap = {};
for (const set of sets) {
const colorWithCount = set.split(",");
for (const colorCount of colorWithCount) {
const [count, color] = colorCount.trim().split(" ");
const countAsNum = Number(count);
const currentMax = gameMaxMap[color] || 0;
if (countAsNum > currentMax) {
gameMaxMap[color] = countAsNum;
}
}
}
const red = Number(gameMaxMap["red"]) || 0;
const green = Number(gameMaxMap["green"]) || 0;
const blue = Number(gameMaxMap["blue"]) || 0;
const power = red * green * blue;
sum += power;
}
log(sum);
}
part1();
part2();