01020304050607080910111213141516171819202122232425

Advent of Code

2021/1

Sonar Sweep

in C#

by encse

You're minding your own business on a ship at sea when the overboard alarm goes off! You rush to see if you can help. Apparently, one of the Elves tripped and accidentally sent the sleigh keys flying into the ocean!

Before you know it, you're inside a submarine the Elves keep ready for situations like this. It's covered in Christmas lights (because of course it is), and it even has an experimental antenna that should be able to track the keys if you can boost its signal strength high enough; there's a little meter that indicates the antenna's signal strength by displaying 0-50 stars.

Visit the website for the full story and full puzzle description.

using System.Collections.Generic;
using System.Linq;

namespace AdventOfCode.Y2021.Day01;

[ProblemName("Sonar Sweep")]
class Solution : Solver {

    public object PartOne(string input) => DepthIncrease(Numbers(input));

    public object PartTwo(string input) => DepthIncrease(ThreeMeasurements(Numbers(input)));

    int DepthIncrease(IEnumerable<int> ns) => (
        from p in Enumerable.Zip(ns, ns.Skip(1)) 
        where p.First < p.Second 
        select 1
    ).Count();

    // the sum of elements in a sliding window of 3
    IEnumerable<int> ThreeMeasurements(IEnumerable<int> ns) => 
        from t in Enumerable.Zip(ns, ns.Skip(1), ns.Skip(2)) // ⭐ .Net 6 comes with three way zip
        select t.First + t.Second + t.Third;

    // parse input to array of numbers
    IEnumerable<int> Numbers(string input) => 
        from n in input.Split('\n') 
        select int.Parse(n);
}

Please ☆ my repo if you like it!

© 2025 Advent of Code is a registered trademark in the US Images provided by Bing image creator