-
Notifications
You must be signed in to change notification settings - Fork 0
/
day22.test.ts
125 lines (105 loc) · 1.57 KB
/
day22.test.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/* === TYPES === */
/* === PREPARE INPUT === */
export const prepareInput = ([input]: TemplateStringsArray) =>
input
.split("\n\n")
.map((block) => block.split("\n"))
.map<number[]>(([_player, ...deck]) => deck.map(Number)) as [
number[],
number[]
];
/* === UTILS === */
const isEmpty = (arr: unknown[]): boolean => arr.length === 0;
const getScore = (arr: number[]): number =>
[...arr]
.reverse()
.map((n, i) => n * (i + 1))
.reduce((a, b) => a + b, 0);
/* === IMPLEMENTATION === */
const combat = ([deck1, deck2]: [number[], number[]]): [number[], number[]] => {
if (isEmpty(deck1) || isEmpty(deck2)) return [deck1, deck2];
const [top1, ...rest1] = deck1;
const [top2, ...rest2] = deck2;
if (top1 > top2) {
return combat([[...rest1, top1, top2], rest2]);
} else {
return combat([rest1, [...rest2, top2, top1]]);
}
};
/* === TESTS === */
test("Day 22a - test", () => {
const [deck1, deck2] = combat(testInput);
expect(deck2).toEqual([3, 2, 10, 6, 8, 5, 9, 4, 7, 1]);
expect(getScore(deck1) + getScore(deck2)).toBe(306);
});
test("Day 22a - prod", () => {
const [deck1, deck2] = combat(prodInput);
expect(getScore(deck1) + getScore(deck2)).toBe(31629);
});
test.skip("Day 22b - test", () => {});
test.skip("Day 22b - prod", () => {});
/* === INPUTS === */
const testInput = prepareInput`Player 1:
9
2
6
3
1
Player 2:
5
8
4
7
10`;
const prodInput = prepareInput`Player 1:
28
50
9
11
4
45
19
26
42
43
31
46
21
40
33
20
7
6
17
44
5
39
35
27
10
Player 2:
18
16
29
41
14
12
30
37
36
24
48
38
47
34
15
8
49
23
1
3
32
25
22
13
2`;