Advent of Code — Day 10 — Javascript

Image for post
Image for post

For day 10, the explanation of the problem is a bit convoluted and can be simplified quite a bit. The input given is an unordered list of unique numbers where each number accepts a value within the list that is between 1 and 3 lower than the current value.

The question asks for the number of differences of 1 and the number of differences of 3. If this does not make sense, we can take a look at the sample data.

Assuming that the count starts at zero, the next number in the set would be 1. From 0 to 1, the difference is 1. The next number would be 4. From 1 to 4, the difference is 3. Followed by 5 with a difference of 1, 6 with a difference of 1, 7 with a difference of 1, 10 with a difference of 3, and so on and so forth.

By sorting the numbers, we can easily traverse the list and find the value of each difference.

The difference between arr.sort() and arr.sort((a,b) => a — b) in this scenario is that the built-in Javascript .sort() method orders each value by the first characters ASCII value. The latter would sort value by the numerical value of each number.

The other piece of information in our data is that the first index is implied in the question and is not present in the data. The initial value is 0. The last number in the data is also not present. Stated in the question, it is 3 plus the largest number in the data set.

Our data is not set and we need to create a variable to store the count of the differences.

Finally, we can loop through array and obtain the count.

Rereading the problem, Advent of Code asks us to return the product of ones count and threes count.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store