Skip to content

Instantly share code, notes, and snippets.

@ninjacarr
Created December 4, 2023 20:57
Show Gist options
  • Save ninjacarr/6d7206b0841936ace5d731978050d0c1 to your computer and use it in GitHub Desktop.
Save ninjacarr/6d7206b0841936ace5d731978050d0c1 to your computer and use it in GitHub Desktop.
AOC 2023 day 4 solve
const { u } = require("../../tools/utils");
let input = "./input.txt";
//input = "./input_demo.txt";
const lines = u.readInputLines(input);
console.time("runtime");
const cards = lines
.map((line) => line.split(":")[1])
.map((line) =>
line.split("|").map((subline) =>
subline
.trim()
.replaceAll(" ", " ")
.split(" ")
.map((num) => Number(num))
)
);
// Part 1
const cardPoints = [];
const cardMatches = [];
const cardCounts = [];
for (const card of cards) {
const wins = card[0].filter((winning) => card[1].includes(winning)).length;
const points = wins > 1 ? Math.pow(2, wins - 1) : wins;
cardPoints.push(points);
cardMatches.push(wins);
cardCounts.push(1);
}
console.log("Part 1:", cardPoints.reduce((a, c) => (a += c), 0));
// Part 2
for (i = 0; i < cardCounts.length; i++) {
const wins = cardMatches[i];
if (wins > 0) {
for (j = i + 1; j < i + 1 + wins && j < cardCounts.length; j++) {
cardCounts[j] += cardCounts[i];
}
}
}
console.log("Part 2:", cardCounts.reduce((a, c) => (a += c), 0));
console.timeEnd("runtime");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment