Advent of Code F# – Day 18

The source code for this post (both Part 1 and Part 2) is avail­able here and you can click here to see my solu­tions for the oth­er Advent of Code chal­lenges.

Descrip­tion for today’s chal­lenge is here.

 

This is a mod­i­fied ver­sion of the Day 6 chal­lenge, with a twist of course.

So, we’ll start by cre­at­ing a 100x100 2D array to rep­re­sent our grid of lights. As per the instruc­tion, we’ll read the input and use # to set the orig­i­nal state of a light to ON, and . to set the orig­i­nal state of a light to OFF.

day18_01

Next, let’s add a func­tion to count the num­ber of neigh­bours that are ON, whilst tak­ing into account that lights on the edge of the grid won’t have all 8 neigh­bours:

day18_02

Then we’ll sim­u­late 100 steps, each step would use the state from the pre­vi­ous step in a fold:

day18_03

Final­ly, count the num­ber of lights that are ON in the state after 100 steps:

day18_04v2

 

Part 2

All else stays the same, we just need to inject addi­tion­al log­ic to check if the light is one of the cor­ner lights in a few places.

First, let’s add a func­tion to deter­mine if a light is in the cor­ner:

day18_05

and now we need to use it when set­ting the ini­tial state for our grid:

day18_06

as well as when we step from one state to the next:

day18_07

and that’s it. After you made these cou­ple of changes, all the rest of the code from Part 1 would work like before.