01020304050607080910111213141516171819202122232425

Advent of Code

2024/1

Historian Hysteria

in C#

by encse

The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit.

As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th.

Visit the website for the full story and full puzzle description.

namespace AdventOfCode.Y2024.Day01;

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

[ProblemName("Historian Hysteria")]
class Solution : Solver {

    public object PartOne(string input) => 
        // go over the sorted columns pairwise and sum the difference of the pairs
        Enumerable.Zip(Column(input, 0), Column(input, 1))
            .Select(p =>  Math.Abs(p.First - p.Second))
            .Sum();

    public object PartTwo(string input) {
        // sum the elements of the left column weighted by its occurrences in the right
        // ⭐ .Net 9 comes with a new CountBy function
        var weights = Column(input, 1).CountBy(x=>x).ToDictionary();
        return Column(input, 0).Select(num => weights.GetValueOrDefault(num) * num).Sum();
    }

    IEnumerable<int> Column(string input, int column) =>
        from line in input.Split("\n")
        let nums = line.Split("   ").Select(int.Parse).ToArray()
        orderby nums[column]
        select nums[column];
}

Please ☆ my repo if you like it!

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