Advent of Code — Day 10 — Javascript

Vincent Yang
3 min readFeb 22, 2021

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.

16
10
15
5
1
11
7
19
6
12
4

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.

function day10(input){
let arr = input.split('')
arr.sort((a, b) => a - b)
}

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.

16
10
15
5
1
11
7
19
6
12
4
arr.sort()
1
10
11
12
15
16
19
4
5
6
7
arr.sort((a, b) => a - b)
1
4
5
6
7
10
11
12
15
16
19

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.

function day10(input){
let arr = input.split('')
arr.sort((a, b) => a - b)
arr.push(input[input.length - 1] + 3)
arr.unshift(0)
}

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

function day10(input){
let arr = input.split('')
arr.sort((a, b) => a - b)
arr.push(input[input.length - 1] + 3)
arr.unshift(0)
let one = 0
let three = 0
}

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

function day10(input){
let arr = input.split('')
arr.sort((a, b) => a - b)
arr.push(input[input.length - 1] + 3)
arr.unshift(0)
let one = 0
let three = 0
for(let i = 0; i < arr.length; i++){
if(arr[i] - arr[i-1] === 1)
one++
if(arr[i] - arr[i-1] === 3)
three++
}
}

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

function day10(input){
let arr = input.split('')
arr.sort((a, b) => a - b)
arr.push(input[input.length - 1] + 3)
arr.unshift(0)
let one = 0
let three = 0
for(let i = 0; i < arr.length; i++){
if(arr[i] - arr[i-1] === 1)
one++
if(arr[i] - arr[i-1] === 3)
three++
}
return one * three
}

--

--