On Day 4 of Advent of Code, we’re finding which rolls of paper forklifts can access, so we can get further into the North Pole base.
I model the diagram of rolls of paper as a boolean grid. A cell is true if it has a roll.
Finding adjacent positions
To find the adjacent positions, I add -1, 0, 1 to each coordinate, with proper bounds checking.
Here’s my FindAdjacentPositions():
static IEnumerable<bool> FindAdjacentPositions(bool[][] rollsOfPaper, int i, int j)
{
for (int row = -1; row <= 1; row++)
{
for (int col = -1; col <= 1; col++)
{
var x = i + row;
var y = j + col;
if (x >= 0 && x < rollsOfPaper.Length
&& y >= 0 && y < rollsOfPaper[x].Length)
{
if (x == i && y == j)
{
continue;
}
var cell = rollsOfPaper[x][y];
yield return cell;
}
}
}
}
After that, the next step is filtering and counting the rolls with less than 4 neighbor rolls.
Filtering and counting
Here’s my final solution,
var rollsOfPaper = new bool[][]
{
[ false, false, true, true, false, true, true, true, true, false, ],
[ true, true, true, false, true, false, true, false, true, true, ],
[ true, true, true, true, true, false, true, false, true, true, ],
[ true, false, true, true, true, true, false, false, true, false, ],
[ true, true, false, true, true, true, true, false, true, true, ],
[ false, true, true, true, true, true, true, true, false, true, ],
[ false, true, false, true, false, true, false, true, true, true, ],
[ true, false, true, true, true, false, true, true, true, true, ],
[ false, true, true, true, true, true, true, true, true, false, ],
[ true, false, true, false, true, true, true, false, true, false, ],
};
var count = 0;
for (int i = 0; i < rollsOfPaper.Length; i++)
{
for (int j = 0; j < rollsOfPaper[i].Length; j++)
{
if (rollsOfPaper[i][j])
{
var adjacents = FindAdjacentPositions(rollsOfPaper, i, j);
if (adjacents.Count(roll => roll) < 4)
{
count++;
}
}
}
}
Console.WriteLine(count);
Console.ReadKey();
static IEnumerable<bool> FindAdjacentPositions(bool[][] rollsOfPaper, int i, int j)
{
for (int row = -1; row <= 1; row++)
{
for (int col = -1; col <= 1; col++)
{
var x = i + row;
var y = j + col;
if (x >= 0 && x < rollsOfPaper.Length
&& y >= 0 && y < rollsOfPaper[x].Length)
{
if (x == i && y == j)
{
continue;
}
var cell = rollsOfPaper[x][y];
yield return cell;
}
}
}
}
My goal is to use “functionalish” solutions, but two loops and an accumulator were so easy that I stuck with them.
Et voilà!
Advent of Code sharpens your coding skills. But coding is more than typing symbols fast. It’s also about teamwork, collaboration, and many skills I share in my book, Street-Smart Coding: 30 Ways to Get Better at Coding. That’s the roadmap I wish I’d known from day one.