Skip to content

Advent of Code 2021 – Day 1, Puzzle 2

Christmas countdown

Photo by Any Lane from Pexels

I’m participating in the Advent of Code 2021 (@adventofcode). Here’s my solution for Day 1, Puzzle 2 – Three Measurement Sliding Window

Problem

Puzzle 2 involves a more refined measurement of the depth readings by comparing measurements of 3 consecutive readings to the next 3. By that we mean, taking the sum of measurements 1, 2 & 3, and then comparing that to the sum of 2, 3 & 4. If thats an increase, then we count it. We’ll use the same input list of 2000 measurements we used for Puzzle 1.

Solution

All my solutions are written in C#. You can find all my solutions in my Git repo.

The solution is fairly clear. We iterate each row in order, adding the next two rows to its value. Then we get the next three rows and add them, comparing the result to the first sum.

Console.WriteLine("Advent of Code 2021");
Console.WriteLine("Day 1 - Sonar Sweep");
//Solution logic goes here
//Load input array
string[] lines = System.IO.File.ReadAllLines("input.txt");
int[] measurements = new int[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
      measurements[i] = int.Parse(lines[i]);
}
int depth1 = 0, depth2 = 0;
var increases = 0;
for (int i = 0; i < lines.Length - 3; i++)
{
    depth1 = measurements[i] + measurements[i + 1] + measurements[i + 2];
    depth2 = measurements[i + 1] + measurements[i + 2] + measurements[i + 3];
    if(depth2 > depth1) increases++;
}
//Write out the solution
Console.WriteLine($"Number of increases: {increases}");

//Stop and wait for enter before exiting
Console.ReadLine();

The answer is 1653