1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
import fs from "fs";
// Quick implementation of _.chunks
function chunks<T>(data: Array<T>, chunkSize: number) {
return data.reduce((acc, value, index) => {
// Initialize a new chunk
if (index % chunkSize === 0) acc.push([]);
acc[acc.length - 1].push(value);
return acc;
}, [] as T[][]);
}
function parseNumbers(s: string) {
return chunks(s.split(""), 3).map((chunk) => Number(chunk.join("")));
}
const lines = fs
.readFileSync("./input.txt")
.toString()
.split("\n")
.slice(0, -1);
const result = lines
.map((line) => {
const [_cardStr, dataStr] = line.split(": ");
const [winning, existing] = dataStr.split("| ").map(parseNumbers);
return { winning, existing };
})
.map((data) => data.existing.filter((x) => data.winning.includes(x)).length)
.reduce((acc, winCount, index) => {
return acc.map((v, i) =>
i > index && i <= index + winCount ? v + acc[index] : v,
);
}, new Array(lines.length).fill(1))
.reduce((acc, v) => acc + v, 0);
console.log({ result });
|