Advent of Code Day 9: Finding the Largest Rectangle of Red Tiles

On Day 9 of Advent of Code, we’re helping elves to redecorate the theater by rearranging the red tiles on the floor.

After yesterday’s struggle, this is an easy one when I consider every pair of points as the opposite corners of a rectangle to calculate its area. Like this,

record Rectangle(Position Left, Position Right)
{
    public int Area
        => (Math.Abs(Left.Y - Right.Y) + 1)
                * (Math.Abs(Left.X - Right.X) + 1);
}

Then, I reuse Pairs() from yesterday to find all rectangles. Next, I use LINQ’s MaxBy to find the largest one. Like this,

var largest = redTiles.Pairs()
    .Select(p => new Rectangle(p.First, p.Second))
    .MaxBy(r => r.Area);

With those two pieces, the puzzle is solved. Here’s my full solution,

var redTiles = new[]
{
    new Position(7,1),
    new Position(11,1),
    new Position(11,7),
    new Position(9,7),
    new Position(9,5),
    new Position(2,5),
    new Position(2,3),
    new Position(7,3),
};

var largest = redTiles.Pairs()
                    .Select(p => new Rectangle(p.First, p.Second))
                    .MaxBy(r => r.Area);

Console.WriteLine(largest);
Console.ReadKey();

record Position(int X, int Y);
record Rectangle(Position Left, Position Right)
{
    public int Area
        => (Math.Abs(Left.Y - Right.Y) + 1)
                * (Math.Abs(Left.X - Right.X) + 1);
}

internal static class Extensions
{
    public static IEnumerable<(T First, T Second)> Pairs<T>(this IEnumerable<T> self)
    {
        return self.SelectMany((fst, i) => self.Skip(i + 1).Select(snd => (fst, snd)));
    }
}

I deserved some rest from yesterday’s puzzle. Today, I can easily say: Et voilà!

Advent of Code sharpens your coding skills. But coding is more than typing symbols fast. It’s also about teamwork, collaboration, and many skills I share in my book, Street-Smart Coding: 30 Ways to Get Better at Coding. That’s the roadmap I wish I’d known from day one.

Get your copy of Street-Smart Coding here