DEV Community

Derp
Derp

Posted on • Edited on

Advent of Code 2021 - day 1

https://adventofcode.com/2021/day/1

Given a list of numbers, we are asked how many times the next number in the list is larger than the previous. Ie

199 (N/A - no previous measurement)
200 (increased)
208 (increased)
210 (increased)
200 (decreased)
207 (increased)
240 (increased)
269 (increased)
260 (decreased)
263 (increased)
Enter fullscreen mode Exit fullscreen mode

This can be solved by reducing over the array returning back a pair of (lastNumber, count) in the reduction function. For the starting condition, I want to use Number.NaN to ensure that I do not increase the count for the first iteration.

-- Part 2
This time, instead of measuring the difference between individual measurements, we are now measuring a sliding window of three values. Ie in the first example, we measure whether [199, 200, 208] is larger than [200, 208, 210]. Since the only difference between these two frames are the numbers at the front and the end, I am going to use a comparison function that takes in four numbers and compares the first and last numbers which should tell me if there is an increase or not. I will then move my sliding window of four over the original list.

https://codesandbox.io/s/amazing-satoshi-zbcs7?file=/src/index.ts

Top comments (0)