Day 4 complete!
Change-Id: I7016a2872c2b774d03e52c0b4b67baf5a9cbf025
Reviewed-on: https://git.clicks.codes/c/Coded/AoC2023/+/166
diff --git a/day 4/index.ts b/day 4/index.ts
new file mode 100644
index 0000000..8643cc2
--- /dev/null
+++ b/day 4/index.ts
@@ -0,0 +1,78 @@
+import { readFileSync } from "fs";
+
+const input = readFileSync('day 4/input.txt').toString().split('\n');
+
+interface Card {
+ id: number,
+ winningNums: number[],
+ cardNums: number[]
+}
+
+const cards: Card[] = [];
+
+for (const line of input) {
+ const id: number = parseInt(line.match(/Card\s+(\d+)/)![1])
+ const withoutCardId = line.split(': ')[1]
+ const unformattedWinNums = withoutCardId.split('|')[0].trim().replace(/\s+/g, ' ');
+ const unformattedCardNums = withoutCardId.split('|')[1].trim().replace(/\s+/g, ' ');
+ const winningNums = unformattedWinNums.split(' ').map(i => parseInt(i));
+ const cardNums = unformattedCardNums.split(' ').map(i => parseInt(i));
+
+ cards.push({
+ id,
+ winningNums,
+ cardNums
+ })
+}
+
+const findMatches = (card: Card): number[] => {
+ const matches: number[] = []
+ card.cardNums.forEach(num => {
+ card.winningNums.includes(num) ? matches.push(num) : void 0;
+ })
+
+ return matches
+}
+
+// Part 1
+(() => {
+ let sum = 0;
+ for(const card of cards) {
+
+ const matches = findMatches(card);
+ if(!(matches.length > 0)) continue;
+ let mult: number = 0;
+ matches.forEach((i, idx) => {
+ idx === 0 ? mult = 1 : mult *= 2
+ })
+
+ sum += mult ?? 0
+
+ }
+ console.log(`(Part 1) Points: ${sum}`)
+})();
+
+// Part 2
+
+interface newCard extends Card {
+ copies: number
+}
+
+(() => {
+ const newCards: newCard[] = cards.map(card => {
+ return {...card, copies: 1}
+ });
+
+ for(let i = 0; i < newCards.length; i++) {
+ const card = newCards[i]
+ const matchCount = findMatches(card).length;
+ for(let j = matchCount; j > 0; j--) {
+ newCards[i+j].copies += (1 * card.copies);
+ }
+
+ }
+
+ console.log(`(Part 2) Total Scratchcards: ${newCards.reduce((acc, curr) => {
+ return acc + curr.copies;
+ }, 0)}`)
+})();
\ No newline at end of file
diff --git a/day 4/testdata.txt b/day 4/testdata.txt
new file mode 100644
index 0000000..71f208a
--- /dev/null
+++ b/day 4/testdata.txt
@@ -0,0 +1,6 @@
+Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
+Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
+Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
+Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
+Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
+Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
\ No newline at end of file