From ef171aaa3002d71d46bf3ff570157371aa693249 Mon Sep 17 00:00:00 2001 From: Peter Date: Tue, 5 Dec 2023 00:27:17 +0800 Subject: [PATCH] =?UTF-8?q?Day=204=20solutions=20=F0=9F=98=B6=F0=9F=98=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day_4/part_1.ts | 27 +++++++++++++++++++++++++++ day_4/part_2.ts | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 day_4/part_1.ts create mode 100644 day_4/part_2.ts diff --git a/day_4/part_1.ts b/day_4/part_1.ts new file mode 100644 index 0000000..3a46dc3 --- /dev/null +++ b/day_4/part_1.ts @@ -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) +); diff --git a/day_4/part_2.ts b/day_4/part_2.ts new file mode 100644 index 0000000..cbc6525 --- /dev/null +++ b/day_4/part_2.ts @@ -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));