My participation to Advent of Code 2020
- put input entries in an array
numbers
- sort array by ascending order
- start
first
at first element of array - start
second
at last element of array - calculate sum
numbers[first] + numbers[second]
- if sum is less than 2020, move
first
to next element - if sum is greater than 2020, move
second
to previous element - if sum equals 2020, return
numbers[first] * numbers[second]
- if
first
andsecond
point to the same element, no match was found - repeat from calculating the sum
Finding the matching pair of numbers has complexity O(n)
,
which is dominated by complexity of sorting, which is, depending on implementation O(n log n)
.
- Run algorithm of part 1 for each
number
in the array, looking for sum that equals2020 - number
This algorithm has complexity O(n^2)
.
$ nvm use
$ ./day1.js < simple-input-day1.txt
part 1: 514579 part 2: 241861950
or
$ ./day1.awk < simple-input-day1.txt
part 1: 514579 part 2: 241861950