Day 4 solutions 😶😶

This commit is contained in:
Peter 2023-12-05 00:27:17 +08:00
parent c15fe9f069
commit ef171aaa30
2 changed files with 59 additions and 0 deletions

27
day_4/part_1.ts Normal file
View File

@ -0,0 +1,27 @@
import * as fs from "fs";
const input = fs.readFileSync("input", "utf8");
const cards = input.split("\n").map((card) =>
card
.split(": ")[1]
.split(" | ")
.map((part) =>
part
.split(" ")
.filter((num) => num !== "")
.map((num) => parseInt(num))
)
);
console.log(
cards
.map((card) =>
card[1].reduce(
(score, your_number) =>
card[0].includes(your_number) ? (score === 0 ? 1 : score * 2) : score,
0
)
)
.reduce((sum, score) => sum + score, 0)
);

32
day_4/part_2.ts Normal file
View File

@ -0,0 +1,32 @@
import * as fs from "fs";
const input = fs.readFileSync("input", "utf8");
const cards = input.split("\n").map((card) =>
card
.split(": ")[1]
.split(" | ")
.map((part) =>
part
.split(" ")
.filter((num) => num !== "")
.map((num) => parseInt(num))
)
);
const card_dupe_count = Array(cards.length).fill(1);
const get_matching_numbers = (card: number[][]) =>
card[1].reduce(
(score, your_number) => (card[0].includes(your_number) ? score + 1 : score),
0
);
cards.map((card, i) => {
const matching_numbers = get_matching_numbers(card);
[...Array(matching_numbers).keys()].forEach((off) => {
card_dupe_count[i + off + 1] += card_dupe_count[i];
});
});
console.log(card_dupe_count.reduce((sum, v) => sum + v, 0));