Skip to content

Commit 98ce889

Browse files
committed
Add day 9 part 2
1 parent 3a28064 commit 98ce889

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/2020/day9/part2.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import {part1} from './part1';
2+
3+
export const part2 = (input: string, preamble: number) => {
4+
const inputNumbers = input.split('\n').map(Number);
5+
const invalidNumber = part1(input, preamble)!;
6+
const contiguousNumbers = [];
7+
8+
let accumulator = 0;
9+
for (const current of inputNumbers) {
10+
accumulator = contiguousNumbers.reduce((a, b) => a + b, 0);
11+
12+
if (accumulator === invalidNumber) {
13+
return Math.min(...contiguousNumbers) + Math.max(...contiguousNumbers);
14+
}
15+
16+
// Make room for current number
17+
while (accumulator + current > invalidNumber) {
18+
accumulator -= contiguousNumbers.shift()!;
19+
}
20+
21+
contiguousNumbers.push(current);
22+
}
23+
};

src/2020/day9/test.spec.ts

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

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

56
describe('Advent of Code 2020 - Day 9', () => {
67
let input: string;
@@ -37,4 +38,14 @@ describe('Advent of Code 2020 - Day 9', () => {
3738
expect(part1(input, 25)).toBe(50047984);
3839
});
3940
});
41+
42+
describe('part 2', () => {
43+
it('should output 62', () => {
44+
expect(part2(testInput, 5)).toBe(62);
45+
});
46+
47+
it('should output 5407707 from input', () => {
48+
expect(part2(input, 25)).toBe(5407707);
49+
});
50+
});
4051
});

0 commit comments

Comments
 (0)