Skip to content

Commit c9acd1a

Browse files
committed
Add day 10 part 2
1 parent 56a546d commit c9acd1a

File tree

3 files changed

+83
-31
lines changed

3 files changed

+83
-31
lines changed

src/2020/day10/part2.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const countDistinctWays = (input: number[]) => {
2+
const lastIndex = input.length - 1;
3+
const distinctWays = input.reduce(
4+
(distinctWays, adapter, i) => {
5+
// Compare current adapter with the three next neighbours and
6+
// check if the joltage difference less or equal to three.
7+
for (let j = i + 1; j < i + 4; j++) {
8+
if (input[j] - adapter <= 3) {
9+
distinctWays[j] += distinctWays[i];
10+
}
11+
}
12+
return distinctWays;
13+
},
14+
[1, ...Array(lastIndex).fill(0)] // First is always valid
15+
);
16+
return distinctWays[lastIndex];
17+
};
18+
19+
export const part2 = (input: string) => {
20+
const adapters = [0, ...input.split('\n')].map(Number).sort((a, b) => a - b);
21+
adapters.push(adapters[adapters.length - 1] + 3); // 3 higher than the highest-rated adapter.
22+
23+
return countDistinctWays(adapters);
24+
};

src/2020/day10/test.spec.ts

Lines changed: 28 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,15 @@
11
import {readInput} from '../../utils';
22

33
import {part1} from './part1';
4+
import {part2} from './part2';
45

56
describe('Advent of Code 2020 - Day 10', () => {
67
let input: string;
7-
const testInput = `28
8-
33
9-
18
10-
42
11-
31
12-
14
13-
46
14-
20
15-
48
16-
47
17-
24
18-
23
19-
49
20-
45
21-
19
22-
38
23-
39
24-
11
25-
1
26-
32
27-
25
28-
35
29-
8
30-
17
31-
7
32-
9
33-
4
34-
2
35-
34
36-
10
37-
3`;
8+
let testInput: string;
389

3910
beforeAll(async () => {
4011
input = await readInput(__dirname + '/input');
12+
testInput = await readInput(__dirname + '/test_input');
4113
});
4214

4315
describe('part 1', () => {
@@ -63,4 +35,29 @@ describe('Advent of Code 2020 - Day 10', () => {
6335
expect(part1(input)).toBe(2112);
6436
});
6537
});
38+
39+
describe('part 2', () => {
40+
it('should output 8', () => {
41+
const input = `16
42+
10
43+
15
44+
5
45+
1
46+
11
47+
7
48+
19
49+
6
50+
12
51+
4`;
52+
expect(part2(input)).toBe(8);
53+
});
54+
55+
it('should output 19208 ', () => {
56+
expect(part2(testInput)).toBe(19208);
57+
});
58+
59+
it('should output 3022415986688 from input', () => {
60+
expect(part2(input)).toBe(3022415986688);
61+
});
62+
});
6663
});

src/2020/day10/test_input

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
28
2+
33
3+
18
4+
42
5+
31
6+
14
7+
46
8+
20
9+
48
10+
47
11+
24
12+
23
13+
49
14+
45
15+
19
16+
38
17+
39
18+
11
19+
1
20+
32
21+
25
22+
35
23+
8
24+
17
25+
7
26+
9
27+
4
28+
2
29+
34
30+
10
31+
3

0 commit comments

Comments
 (0)