DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Derp
Derp

Posted on • Updated 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)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!