Advent of Code Day 3: Calculating the Joltage of Batteries

On Day 3 of Advent of Code, we’re finding the joltage of a bank of batteries to power an escalator.

Elevators are out of service and the escalator needs the batteries with the higher joltage.

Finding pairs of batteries

I use brute force to find all battery pairs.

Two for loops didn’t feel old-schoool. So I borrow a LINQ query from this StackOverflow answer.

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)));
    }
}

Calculating the joltage

Once we have the pairs, I need two methods to calculate joltage: for a pair and for a bank.

static int FindJoltage(Bank bank)
    => bank.Batteries.Pairs().Select(FindJoltageOfPair).Max();

static int FindJoltageOfPair((int Battery1, int Battery2) pair)
    => pair.Battery1 * 10 + pair.Battery2;

Here’s my full solution:


var allBanks = new List<Bank>
{
    new Bank([ 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1 ]),
    new Bank([ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9 ]),
    new Bank([ 2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 7, 8 ]),
    new Bank([ 8, 1, 8, 1, 8, 1, 9, 1, 1, 1, 1, 2, 1, 1, 1 ])
};
var totalJoltage = allBanks.Select(FindJoltage).Sum();
Console.WriteLine(totalJoltage);
Console.ReadLine();

static int FindJoltage(Bank bank)
    => bank.Batteries.Pairs().Select(FindJoltageOfPair).Max();

static int FindJoltageOfPair((int Battery1, int Battery2) pair)
    => pair.Battery1 * 10 + pair.Battery2;

record Bank(IEnumerable<int> Batteries);

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)));
    }
}

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