Advent of Code — Day 2 — Javascript

Vincent Yang
3 min readDec 29, 2020

For Day 2, you are given a list, each with their own rules and asked to return the number of lines that are valid.

1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc

In the example provided, you are given three lines. The numbers before and after the dash tell you how many times the following letter should appear in the string on the right side of the colon. In the line: 1-3 a: abcde, the letter a should appear between one and three times in the string after the colon.

For the example above, the answer would be 2. For the first line, the letter ‘a’ appears in the string between one and three times. In the second line, the letter ‘b’ does not appear in the string at all and should return false. In the third line, the letter ‘c’ appears nine times which is within the specified limit.

If the entire dataset were passed into function as is, it would be passed in as a string and would need to be parsed. In order to check each individual line for truthiness, we would need to use the .split(‘\n’) function in order to divide each piece of data by the newline character into it’s own individual piece to be accessed in an array. Currently, our code should look something like this:

function day2(str){
const arr = str.split('\n')
}
day2('
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
')

With this, the data will look something like this:

console.log(arr)
// ['1-3 a: abcde','1-3 b: cdefg','2-9 c: ccccccccc']
// Where arr[0] = '1-3 a: abcde'

Now that we can access each line individually, we can break down each line to parse the data. We can divide each element into a left and right side — the pattern and the data.

function day2(str){
let counter = 0
const arr = str.split('\n')
for(let i = 0; i < arr.length; i++){
let eachLine = arr[i].split(':')
let pattern = eachLine[0]
let data = eachLine[1]
}
}

Just looking at the first line of the instructions that we were provided, the data now looks something like this:

//arr[0] = '1-3 a: abcde'
//eachLine = ['1-3 a','abcde']
//pattern = '1-3 a'
//data = abcde

We’re almost there and we just need a few more .split() functions to get the individual pieces of data into their own variables. The final version should look something like this.

function day2(str){
let counter = 0
const arr = str.split('\n')
for(let i = 0; i < arr.length; i++){
let eachLine = arr[i].split(':')
let smallBound = eachLine[0].split('-')
let bigBound = smallBound[1].split(' ')
let letter = bigBound[1]
let count = 0
for(let i = 0; i < arr[x].length; i++){
if(splitStr[1][i] === letter){
count++
}
}
count >= smallBound[0] && count <= bigBound[0] ? counter++ : null
}
return counter
}

After getting each piece of data into their individual variables, parse through the right side of the string and count and see if the number of appearances in between the specified numbers. You should do this for each line and increment the true counter that was created at the top.

--

--