01020304050607080910111213141516171819202122232425

Advent of Code

2023/3

Gear Ratios

in C#

by encse

Let's revisit the problem description here.

There are multiple ways to footgun ourselves with this one, if somebody is not careful with the parser. I solved this problem using regular expressions. First I searched for all numbers and symbols, then collected those that were adjacent to each other.

I did the same trick in Part 2, but now searched for all gear symbols (*) and filtered out those that are adjacent to exactly two numbers.

Probably the hardest part is to tell if two matches are adjacent or not.

namespace AdventOfCode.Y2023.Day03;

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

[ProblemName("Gear Ratios")]
class Solution : Solver {

    // Introduce a Parse function that returns the interesting 'blocks' of texts 
    // and positions using a regex. Then just filter and match these according
    // to the problem spec.

    public object PartOne(string input) {
        var rows = input.Split("\n");
        var symbols = Parse(rows, new Regex(@"[^.0-9]"));
        var nums = Parse(rows, new Regex(@"\d+"));

        return (
            from n in nums
            where symbols.Any(s => Adjacent(s, n))
            select n.Int
        ).Sum();
    }

    public object PartTwo(string input) {
        var rows = input.Split("\n");
        var gears = Parse(rows, new Regex(@"\*"));
        var numbers = Parse(rows, new Regex(@"\d+"));

        return (
            from g in gears
            let neighbours = from n in numbers where Adjacent(n, g) select n.Int
            where neighbours.Count() == 2
            select neighbours.First() * neighbours.Last()
        ).Sum();
    }

    // checks that the parts are touching each other, i.e. rows are within 1 
    // step and also the columns (using https://stackoverflow.com/a/3269471).
    bool Adjacent(Part p1, Part p2) =>
        Math.Abs(p2.Irow - p1.Irow) <= 1 &&
        p1.Icol <= p2.Icol + p2.Text.Length &&
        p2.Icol <= p1.Icol + p1.Text.Length;

    // returns the matches of rx with its coordinates
    Part[] Parse(string[] rows, Regex rx) => (
        from irow in Enumerable.Range(0, rows.Length)
        from match in rx.Matches(rows[irow])
        select new Part(match.Value, irow, match.Index)
    ).ToArray();
}

record Part(string Text, int Irow, int Icol) {
    public int Int => int.Parse(Text);
}

Please ☆ my repo if you like it!

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