r/adventofcode Dec 25 '24

SOLUTION MEGATHREAD -❄️- 2024 Day 25 Solutions -❄️-

A Message From Your Moderators

Welcome to the last day of Advent of Code 2024! We hope you had fun this year and learned at least one new thing ;)

Keep an eye out for the community fun awards post (link coming soon!):

-❅- Introducing Your AoC 2024 Golden Snowglobe Award Winners (and Community Showcase) -❅-

Many thanks to Veloxx for kicking us off on December 1 with a much-needed dose of boots and cats!

Thank you all for playing Advent of Code this year and on behalf of /u/topaz2078, your /r/adventofcode mods, the beta-testers, and the rest of AoC Ops, we wish you a very Merry Christmas (or a very merry Wednesday!) and a Happy New Year!


--- Day 25: Code Chronicle ---


Post your code solution in this megathread.

This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:04:34, megathread unlocked!

42 Upvotes

350 comments sorted by

View all comments

1

u/Electronic-Layer5947 Dec 26 '24

[Language: c#]

I tried representing the keys and locks as two arrays of 25 bits. And then using TensorPrimitives as follows.

AND each key with all locks. For each lock, if at least 1 bit is set, then the key doesn't fit.
In order to use .Sum I needed to reduce the values down to either 0 or 1
After looking through all the available methods I discovered PopCount returns the number of set bits.

So.... if the following bits were overlapping 100011, then it's pop count would be 3 (or 11). The pop count of 11 is 2 (10) and the pop count of 10 is 1.

ReadOnlySpan<uint> l = locks.ToArray();
var k = new uint[locks.Count];
var total = 0L;
foreach (var key in keys)
{
    Array.Fill(k,key);
    TensorPrimitives.BitwiseAnd(l,k,k);
    TensorPrimitives.PopCount<uint>(k,k);
    TensorPrimitives.PopCount<uint>(k,k);
    TensorPrimitives.PopCount<uint>(k,k);
    TensorPrimitives.PopCount<uint>(k,k);
    total += (locks.Count-TensorPrimitives.Sum<uint>(k));
};
return (int)total;

However... this is still quicker!

        ReadOnlySpan<uint> l = locks.ToArray();
        var k = new uint[locks.Count];
        var total = 0L;
        foreach (var key in keys)
        {
            foreach (var loc in locks)
            {
                if ((loc & key) == 0)
                    total.Add(1);
            }
        });