01020304050607080910111213141516171819202122232425

Advent of Code

2024/2

Red-Nosed Reports

in C#

by encse

Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office.

While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron.

Visit the website for the full story and puzzle description.

I created a function to check the validity of a single input line. This is achieved using the usual method of zipping the input with itself to generate a list of consecutive pairs. The next step involves checking the monotonicity condition (either increasing or decreasing) for each pair.

The second part of the problem is addressed with another helper function. This function takes an input sequence and generates attenuated versions of it in all possible ways, by omitting zero or one elements from the sample.

namespace AdventOfCode.Y2024.Day02;

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

[ProblemName("Red-Nosed Reports")]
class Solution : Solver {

    public object PartOne(string input) => 
        ParseSamples(input).Count(Valid);

    public object PartTwo(string input) => 
        ParseSamples(input).Count(samples => Attenuate(samples).Any(Valid));

    IEnumerable<int[]> ParseSamples(string input) => 
        from line in input.Split("\n")
        let samples = line.Split(" ").Select(int.Parse)
        select samples.ToArray();

    // Generates all possible variations of the input sequence by omitting 
    // either zero or one element from it.
    IEnumerable<int[]> Attenuate(int[] samples) =>
        from i in Enumerable.Range(0, samples.Length+1)
        let before = samples.Take(i - 1)
        let after = samples.Skip(i)
        select Enumerable.Concat(before, after).ToArray();

    // Checks the monothinicity condition by examining consecutive elements
    bool Valid(int[] samples) {
        var pairs = Enumerable.Zip(samples, samples.Skip(1));
        return
            pairs.All(p => 1 <= p.Second - p.First && p.Second - p.First <= 3) ||
            pairs.All(p => 1 <= p.First - p.Second && p.First - p.Second <= 3);
    }
}

Please ☆ my repo if you like it!

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