## DEV Community # Like a GIF For Your Yard

## Advent of Code 2015 Day 18

### Striving for 4/4 stars

• I skipped today's puzzle to complete Day 6
• Thankfully, Day 6 was relatively easy, and I earned two stars
• I hope I can earn two stars today, too
• Let's do it!

## Part 1

1. The origin of this puzzle theme?
2. Writing a working algorithm

### The origin of this puzzle theme?

• In years past, this puzzle theme occurred around the same time: Days 15-25
• This puzzle's instructions feel comprehensive and introductory
• Making me think that today's puzzle was the first of its kind in this first year of puzzles
• I'm just glad it's not the first time I'm encountering it
• To the contrary, it seems very doable given all my previous successful encounters

### Writing a working algorithm

Parsing the input into a grid of nested arrays:

``````input.split('\n')
.map(line => line.split(''))
``````

Relative coordinates of all eight adjacent cells:

``````adjacents = [
[-1,-1],
[-1, 0],
[-1, 1],
[ 0,-1],
[ 0, 1],
[ 1,-1],
[ 1, 0],
[ 1, 1]
]
``````

Iterate through each of the 10,000 cells in the grid:

``````for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
// access each cell
}
}
``````

Count `on` and `off` lights in adjacent cells:

``````let neighbors_on = adjacents.map(coord =>
grid[row + coord] == undefined ||
grid[row + coord][col + coord] == undefined
? 0 : grid[row + coord][col + coord] == '#'
? 1 : 0
).reduce((lights_on, current) => lights_on + current)
``````

Queue up each light that must change:

``````let changers = []

if (grid[row][col] == "#" && ![2,3].includes(neighbors_on)) {
changers.push([row, col, "."])
} else if (grid[row][col] == "." && neighbors_on == 3) {
changers.push([row, col, "#"])
}
``````

Return the count of lights that are `on`:

``````return [
...grid.map(
el => el.join('')
).join('\n')
.matchAll(/#/g)
].length
``````

It generated the correct answer for my puzzle input!

## Part 2

1. Another disappointment
2. One more loop in each iteration

### Another disappointment

• Much like with Day 6, I was hoping there would be a message or picture revealed after a certain number of light-changing rounds
• Instead, just a simple change to the rules and another count after the same number of iterations

### One more loop in each iteration

The list of four corner coordinates:

``````let corners = [[0,0],[99,0],[99,99],[0,99]]
``````

Ensuring each one is left on at the end of each iteration:

``````corners.forEach(coord => {
grid[coord][coord] = "#"
})
``````

It generated the correct answer for my puzzle input!

## I did it!!!!

• I solve both parts!
• Thus, I earned all four stars from each part of both days!
• I wrote yet another adjacent-cell checking, queuing and changing algorithm!
• I built a simulator to re-create the light show!