File tree Expand file tree Collapse file tree 2 files changed +34
-0
lines changed Expand file tree Collapse file tree 2 files changed +34
-0
lines changed Original file line number Diff line number Diff line change 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+ } ;
Original file line number Diff line number Diff line change 11import { readInput } from '../../utils' ;
22
33import { part1 } from './part1' ;
4+ import { part2 } from './part2' ;
45
56describe ( '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} ) ;
You can’t perform that action at this time.
0 commit comments