-
Notifications
You must be signed in to change notification settings - Fork 0
/
day04.ts
46 lines (34 loc) · 973 Bytes
/
day04.ts
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
38
39
40
41
42
43
44
45
46
import _ from "lodash";
import fs from "fs";
const cards: string[] = _.reject(
fs.readFileSync("inputs/day4.txt", "utf-8").split("\n"),
_.isEmpty
);
const numMatching = (card: string): number => {
const numbers = card.split(": ")[1];
const [winning, yours] = numbers
.split(" | ")
.map((side) => _.reject(side.split(" "), _.isEmpty));
return _.intersection(winning, yours).length;
};
// Part 1
const cardPointValue = (card: string): number => {
const both = numMatching(card);
if (both === 0) {
return 0;
}
return Math.pow(2, both - 1);
};
console.log(_.sum(cards.map(cardPointValue)));
// Part 2
const getTotalCopies = (): number => {
const counts = _.times(cards.length, _.constant(1));
cards.forEach((card, i) => {
const both = numMatching(card);
for (let j = i + 1; j < Math.min(cards.length, i + 1 + both); j++) {
counts[j] += counts[i];
}
});
return _.sum(counts);
};
console.log(getTotalCopies());