01020304050607080910111213141516171819202122232425

Advent of Code

2024/3

Mull It Over

in C#

by encse

"Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look.

The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?"

Visit the website for the full story and puzzle description.

I took a functional approach today. Regular expressions are ugly beasts, I normally try avoid them. Fortunately, we're not writing production code here. Otherwise... everything is just a fold if you look at it from a distance.

namespace AdventOfCode.Y2024.Day03;

using System.Linq;
using System.Text.RegularExpressions;

[ProblemName("Mull It Over")]
class Solution : Solver {

    public object PartOne(string input) => Solve(input, @"mul\((\d{1,3}),(\d{1,3})\)");

    public object PartTwo(string input) => Solve(input, @"mul\((\d{1,3}),(\d{1,3})\)|don't\(\)|do\(\)");

    long Solve(string input, string rx) {
        // overly functionaly approach...
        var matches = Regex.Matches(input, rx, RegexOptions.Multiline);
        return matches.Aggregate(
            (enabled: true, res: 0L), 
            (acc, m) => 
                (m.Value, acc.res, acc.enabled) switch {
                    ("don't()", _, _)  => (false, acc.res),
                    ("do()", _, _)     => (true, acc.res),
                    (_, var res, true) => 
                        (true, res + int.Parse(m.Groups[1].Value) * int.Parse(m.Groups[2].Value)),
                    _ => acc
                },
            acc => acc.res
        );
    }
}

Please ☆ my repo if you like it!

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