Advent of Code — Day 3— Javascript

Vincent Yang
2 min readJan 4, 2021

--

Advent of code

For Day 3, you are navigating a map of ‘.’s and ‘#’s that represent a safe or unsafe point to drive through. The sample data is given as such below:

..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#

The periods on the map represent a clear space to steer through, while a hashtag represents a tree. Given a slope, we are asked to find the number of trees that one would encounter while traversing to the last line of the map. We are also told that once we run off the right side of the map, the pattern of the map repeats. The data would look something like this:

..##.........##.........##.......
#...#...#..#...#...#..#...#...#..
.#....#..#..#....#..#..#....#..#.
..#.#...#.#..#.#...#.#..#.#...#.#
.#...##..#..#...##..#..#...##..#.
..#.##.......#.##.......#.##.....
.#.#.#....#.#.#.#....#.#.#.#....#
.#........#.#........#.#........#
#.##...#...#.##...#...#.##...#...
#...##....##...##....##...##....#
.#..#...#.#.#..#...#.#.#..#...#.#

Similar to the previous problems, we would use .split(‘\n’) and navigate each line of the map.

function day3(input){
const arr = input.split('\n')
//arr[0] = ["..##......."]
//arr[1] = ["#...#...#.."]
//arr[2] = [".#....#..#."]
...
}

We are given a slope of right 3 and down 1 (or m = -3 in math terms). As we know that we will be traversing each line of the map given the instructions (down 1), we will be able to use a for loop in this case. We will need a separate variable in order to keep track of the position on each line as we will need to increment by 3 (right 3).

function day3(input){
const arr = input.split('\n')
let across = 0 //Counter for position in each string
let trees = 0 //Counter for trees encountered
for(let i = 0; i < arr.length; arr++){
if(arr[i][across] === "#"){ //Checks arr[0] at index 0
trees++
}
}
}

Currently, our function only checks the first character of each line to see if it is a tree. We will need to increment across while simultaneously making sure that the pattern repeats when it runs off the map.

function day3(input){
const arr = input.split('\n')
let across = 0
let trees = 0
for(let i = 0; i < arr.length; arr++){
if(arr[i][across] === "#"){
trees++
}
across += 3
if(across > arr[i].length - 1){
across %= arr[i].length
}
}
return trees
}

The for loop while handling going down each line, while the variable ‘across’ makes sure that every time we run off the map, it will run to the start of the map. Given the above input, the return value is 7.

--

--

No responses yet