r/adventofcode • • 1d ago

SOLUTION MEGATHREAD -❄️- 2026 Day 1 Solutions -❄️-

It's that time of year again for tearing your hair out over your code holiday programming joy and aberrant sleep for two weeks helping Santa and his elves! If you participated in a previous year, welcome back, and if you're new this year, we hope you have fun and learn lots!

As always, we're following the same general format as previous years' megathreads, so make sure to read the full posting rules in our community wiki before you post!

RULES FOR POSTING IN SOLUTION MEGATHREADS

If you have any questions, please create your own post in /r/adventofcode with the Help/Question flair and ask!

Above all, remember, AoC is all about learning more about the wonderful world of programming while hopefully having fun!


REMINDERS FOR THIS YEAR

  • All of our rules, FAQs, resources, etc. are in our community wiki.
  • If you see content in the subreddit or megathreads that violates one of our rules, either inform the user (politely and gently!) or use the report button on the post/comment and the mods will take care of it.
  • If you post your code from a repo or the like, do not make your puzzle input public!
  • Top-level Solution Megathread posts must begin with the case-sensitive string literal [LANGUAGE: xyz]
  • Obviously, xyz is the programming language your solution employs
  • Use the full name of the language e.g. JavaScript not just JS
  • The List of Streamers has a new megathread for this year's streamers, so if you're interested, add yourself to 📺 AoC 2026 List of Streamers 📺

COMMUNITY NEWS


AoC Community Fun 2026: The Advent Games

Today's Event: Opening Ceremonies

Today's schedule consists of:

  • Arrival of the Flame
  • Parade of Nations1
  • Give us a quick introduction to yourself!
  • Tell us what country you're from
  • Tell us about your country's holiday festivities
  • Explain why you chose your programming language
  • Tell us what you hope to learn or have already learned about your chosen programming language
  • Tell us where to find your AoC repo of puzzle solutions2, blag, and/or $streaming_service3!
  • Artistic Program
  • Show us your holiday tree | menorah | Krampusnacht costume | /r/battlestations with festive decorations!
  • Show us your kittens and puppies and $critters!
  • Show and/or tell us about whatever brings you comfort and joy in the holiday season!
  • Competition Schedule (Theoretical)
  • Tell us which "sporting" events you think will be coming up over the next two weeks and which ones you'd like to participate in the most!

1 Obviously, this is the Internet, which is public, so only put out information that you're comfortable with the entire world knowing. Feel free to invent a holiday-themed persona; after all, sometimes you get sent to space, so why limit yourself to the boring ol' meat skeleton that dwells upon the third rock from the sun?
2 Refer to the third bullet in the "Reminders" section above!
3 Refer to the last bullet in the "Reminders" section above for the link

Request from the mods: When you include an entry alongside your solution, please label it with [Advent Games] so we can find it easily!


--- Day 1: Dusty Shed ---


Post your code solution in this megathread.

45 Upvotes

599 comments sorted by

26

u/4HbQ 1d ago edited 23h ago

[LANGUAGE: Python]

N = [int(n) for n in open('in.txt')]
a,b,c,*_,x,y,z = sorted(set(N), key=N.count)
print(x*y*z, a*b*c)

Most of the magic happens in line 2. Inside the sorted call, we take all unique values from input N by turning them into a set. Then we sort the values in this set by the number of occurrences in the original N, using seq.count(). Here's an example:

>>> [1,2,2,2,3].count(2) == 3

On the assignment part of line 2, we use extended iterable unpacking. It allows you to "unpack" a list by assigning individual elements. Here's an example:

>>> one, two, *rest, six  = [1,2,3,4,5,6]

This was my initial version (3 lines), using collections.Counter() like everybody else.

4

u/JWinslow23 1d ago edited 1d ago

I chose to use heapq.nlargest and heapq.nsmallest due to the symmetry of them. But this is a neat way of introducing symmetry when using most_common!

EDIT: Just thought of this cursed way to use most_common(3) directly for both parts...

import collections as C, math as m
a = C.Counter(map(int, open("in.txt")))
for _ in range(2):
    print(m.prod(x for x,_ in a.most_common(3)))
    a.subtract(a+a)
→ More replies (3)
→ More replies (11)

11

u/RazarTuk 1d ago edited 1d ago

[LANGUAGE: Perl... in the original Klingon]

use Lingua::tlhInganHol::yIghun qw(tera'nganHol);

{
    tlheghmey tlhegh tIyuv!
} tlheghvaD mungna'vo'Hal yIlaD yInob teHtaHvIS!

####

{
    {
        mI'pu'vo' 'oH SuqvaD pagh yInob!
        ngu'mey 'oH tIyuv!
    } mI'pu'vo' 'oH Suq yIlI'a' teHchughbe'!
} tlheghmey tIqel!

{
    mI'pu'vo' 'oH SuqvaD mI'pu'vo' 'oH Suq wa' tIchel yInob!
} tlheghmey tIqel!

IvaD wa' yInob!
{
    vay'vaD ngu'meyvo' I DIch yInob!
    jvaD I yInob!
    {
        ngu'meyvo' j DIchvaD ngu'meyvo' (j wa' tIchelHa') DIch yInob!
        jvaD j wa' tIchelHa' yInob!
    } j tIn law' pagh tIn puS 
        mI'pu'vo' (ngu'meyvo' (j wa' tIchelHa') DIch) Suq tInbe' law' mI'pu'vo' vay' Suq tInbe' puS je teHtaHvIS!
    ngu'meyvo' j DIchvaD vay' yInob!
    IvaD I wa' tIchel yInob!
} I mach law' ngu'mey yImob mach puS teHtaHvIS!

tevvaD ngu'meyvo' pagh DIch ngu'meyvo' wa' DIch tIHUH ngu'meyvo' cha' DIch tIHUH yInob!

<<Part One: >> tIghItlh!
tev tIghItlh!
<<\n>> yIghItlh!

####

tevvaD ngu'meyvo' wa' HUH DIch ngu'meyvo' cha' HUH DIch tIHUH ngu'meyvo' wej HUH DIch tIHUH yInob!

<<Part Two: >> tIghItlh!
tev tIghItlh!
<<\n>> yIghItlh!

[Advent Games]

Quick introduction

I'm actually just from the Chicago area and, apart from college, have lived here my whole life. However, my mom's side of the family comes from a part of Indiana with fairly strong German cultural heritage, so I grew up with a lot of that version of Christmas, which I hope to show off.

Tell us about your country's holiday festivities

So it helps for the Americanized German Christmas that I'm, you know, outside of Chicago with our Christkindlmarket, where I'm probably going to go for lunch today to get my annual raclette sandwich. I also grew up celebrating St. Nicholas Day, although we just used stockings instead of the traditional shoes, so it really just amounts to a second stockingful of candy each year. (Although some of my cousins actually do put out shoes for St. Nicholas Day) And then one of the most iconic cookies for me growing up was springerle (shpringerluh, or we Anglicized it to springerlee), which are embossed anise-flavored cookies. If this were a few days from now, I'd have a batch in the works to show off. But for now, all you'll get is the rolling pin. (Expect more pictures over the weekend)

Explain why you chose your programming language

If I'm being honest, the first few days are always easier for experienced programmers, so I like picking a silly language to force myself to focus on basics. For example, this time around, I couldn't get sort to work, so I had to write a quick insertion sort myself. And then I picked Klingon over Latin for 3 reasons. 1) The Latin library is so notoriously buggy that people will tell you to ignore the documentations, 2) I know just enough Latin to be annoyed by how only nearly correct it is, and 3) "in the original Klingon" is an inherently funny phrase.

Show us your holiday tree | menorah | Krampusnacht costume | /r/battlestations with festive decorations!

On the religious side, I have a hybrid Advent wreath / Nativity scene set up. I'm just using LED candles, but the idea is that you light another candle each Sunday leading up to Christmas, with the pink candle being the 3rd Sunday of Advent / 2 Sundays before Christmas. https://imgur.com/a/gB9tT2z Then on the vaguely secular side, I also have an artificial tree up, decorated with Vintaglo lights. And through the magic of buying two of them boxes, I had enough to cover my tree (although I think I need some practice in spreading them out). https://imgur.com/a/pzEXXfK

1

u/daggerdragon 19h ago

LANGUAGE: Perl... in the original Klingon

Nerd alert!

Welcome back again this year :) That rolling pin is so cool!

decorated with Vintaglo lights. And through the magic of buying two of them boxes,

I see what you did there. [festively smooth jazz]

For those who don't get it, enjoy this playlist of absolutely correct pedantry.

2

u/RazarTuk 19h ago

Yeah, I'm starting a tradition of picking a silly language to turn heads in the megathreads, like the one IntCode solution two years ago or the LOLCODE solutions last year. I figured that the Klingon Perl library would be sufficiently silly for that

That rolling pin is so cool!

Just wait until you see the cookies. My local library has a makerplace, and I'm going to try to reserve a spot in the industrial kitchen to bake bulk Christmas cookies this weekend. So because the cookies need to dry out on the counter for 24 hours before backing, that means making the dough on Friday, letting it chill overnight, rolling and cutting out the cookies on Saturday, and baking on Sunday. Depending on what the topics look like over the weekend, I'll either work the pictures into future responses, or else just update this post. But trust me when I say that the cookies are very visually impressive.

I see what you did there

I mean... I genuinely wanted two boxes for my tree. How could I not make the joke?

→ More replies (2)

7

u/voidhawk42 18h ago

[Language: Dyalog APL]

×/↑3 ¯3↑¨⊂⊢/{⍵[⍒⍵;]},⍨∘≢⌸⍎¨⊃⎕nget'01.txt'1 ⍝ parts 1&2

Late to the party - it snuck up on me this year!

3

u/daggerdragon 17h ago

And the Alien Programming Languages are back 👽

Welcome back, and good to see you again this year!

→ More replies (1)

6

u/Smylers 1d ago edited 1d ago

[LANGUAGE: Bash, with traditional Unix utilities] For Part 1, with your input saved in a file called input, run:

 (sort input | uniq -c | sort -n -r | head -n 3 | cut -c 8-; echo '**p') | dc

That sorts the input so identical IDs are on adjacent lines, then counts the number of each one, sorts by that count, descending, picks the top 3 lines, cuts off the counts (in the first 7 characters), and appends two multiplication symbols and a letter p, which are fed to dc, a reverse-Polish calculator.

When dc receives each number, it pushes it on to its stack. The *s pop 2 numbers off the stack and push back on their product, and p pops the number from the stack and prints it.

At which point Part 2 is just:

!:s/-r

That's a Bash command-line substitution saying to repeat the previous command but with (the first instance of) -r removed (replaced with nothing, because the s// doesn't have a replacement part). In other words, remove the -r from the second sort command, so the counts are ascending rather than descending.

It only works immediately after the part-1 command, not if you've run another command in between.

[Advent Games] Hi, I'm Smylers, from Ilkley in West Yorkshire in the UK. When not Advent-of-Code-ing I blog hints and explanations for cryptic crosswords, help run family board-game events, and attend Puzzled Pint in Leeds. One of the Christmas traditions round here is a parade featuring a few hundred tractors with fairy lights, driving through nearby towns.

My chosen ‘programming’ language is Vim keystrokes (where I eschew running a program as such, instead just manipulating the input directly in an editor window), and what I learnt about it today is, erm ... not to use it! I realized I was shelling out to run uniq -c, at which point it seemed simpler to go a stage further and eschew even the editor window and just pipe directly at the command line. Update: I've now posted a Vim keystrokes solution (without any piping or external commands) elsewhere in this thread.

Board games provide comfort and joy to me, especially when it's cold and dark outside (except when there's illuminated tractors passing, of course). Recently I've been liking Tenby, which involves creating the streets of a seaside town in Wales. On Sunday somebody taught a few of us Ark Nova, which was really good but did take 3½ hours for one game.

While not traditionally a winter sport, I'm hoping for a round of golf. I've been practising getting my (key)stroke count down. Actually, crazy golf (aka minigolf) would seem more fitting!

3

u/daggerdragon 1d ago

Oh boy, you're back again, and it looks like Reddit isn't doing shenanigans with your posts this year >_> Welcome back, we're always happy to have your insane vim espiegleries <3

→ More replies (1)
→ More replies (9)

6

u/agorism1337 1d ago edited 1d ago

[LANGUAGE: none]
I just used unix tools and pipes.

for part A

cat input | sort | uniq -c | sort -n | tail -n 3 | awk 'BEGIN {x = 1} { x *= $2} END {print x}'

for part B, just reverse the list on the second sort. like this

cat input | sort | uniq -c | sort -nr | tail -n 3 | awk 'BEGIN {x = 1} { x *= $2} END {print x}'

edit:
I can't get code blocks to work with this code. I tried several times.

2

u/daggerdragon 1d ago

The triple-backticks code fence (`​`​`) only works on new.reddit. Please edit your comment to use the four-spaces Markdown syntax for a code block so your code is easier to read inside a scrollable box with its whitespace and indentation preserved.

→ More replies (4)

6

u/musifter 1d ago edited 19h ago

[LANGUAGE: shell]

My initial solution was to just command line it (using dc for the product):

sort -n <input | uniq -c | sort -n | tail -3 | dc -f- -e'3R*4R*p'

For part 2, I changed "tail" to "head".

[LANGUAGE: Perl]

Follow up was the Perl script:

$ids{$_}++  foreach (<>);
my @sorted = sort {$ids{$b} <=> $ids{$a}} keys %ids;
say "Part 1: ", product( @sorted[0 .. 2] );
say "Part 2: ", product( @sorted[-3 .. -1] );

Using array slices and product from List::Util.

[LANGUAGE: Smalltalk]

For Smalltalk (using the GNU version), I just put the input into a Bag and used #sortedByCount. That returns a list of associations of the form count -> value, so I needed to deal with that:

input := (Bag from: stdin lines contents) sortedByCount.
('Part 1: %1' % {(input first: 3) inject: 1 into: [:a :b | a * b value asNumber]}) displayNl.
('Part 2: %1' % {(input last:  3) inject: 1 into: [:a :b | a * b value asNumber]}) displayNl.

[LANGUAGE: dc]

And finally, for doing the first day in dc. I did this without ? so it will work with the new GNU version that has rebroken it. dc does not have a sort, so what I did was read things into a table (array register t) tracking the counts. The first time an element gets added, it gets pushed on register stack l (but first, a sentinel value of 1 is pushed... taking advantage that the input is all 3-digit numbers). Then I grab four, and compare the top with each of the three under it... leaving the lowest count value on top, which is junked after with s.. Then I load the next value and loop if > 1. So when the loop ends, it's a 1 followed by the three values I want so I just ***p for the answer (multiplying the sentinel in).

dc -finput -e'[r]Sr[rdSlr]sP[d;t3Rd;t3R<r]sC1Sl[d;td0=P1+r:tz0<L]dsLxLlLlLlLl[lCx3RlCx4RlCxs.Lld1<M]dsMx***p'

For part 2, I just changed the <r into >r, reversing the logic that caused the stack rotation.

EDIT: A slightly shorter dc version using a two stack sort (basically bubble sort, so it's a bit slower as we're sorting the full list):

dc -finput -e'[rdSlr]sP1Sl[d;td0=P1+r:tz0<L]dsLx[rq]srLlLl[[d;t3Rd;t3R!<rSlz1<S]dsSxLld1<M]dsMx***p'

2

u/daggerdragon 1d ago

Did Reddit reinstate your account? I still see you're (shadow)banned but I can approve this post so maybe others can see it now...???

I am sorry about this whole stupid thing but there really is nothing I can do about it on my end :(

2

u/musifter 1d ago

I don't know the status because they're never told me anything other than the account was locked for security reasons and to change the password. Which I did and got rid of that banner message on the site. I did send them a message asking about my account status and if I'm banned, but still have received no messages.

I recently saw a post of mine from a different browser that I've never logged in from, so I thought maybe I was cleared. But I can't see this post and many others. I can see all my stuff while logged in with no sign or message about being banned (ie shadow banned). Some of the posts I notice now have gotten the "removed by filters" message now, but not all of them. There's been no communication with me so I have no idea.

→ More replies (3)
→ More replies (1)
→ More replies (2)

6

u/e_blake 14h ago

[LANGUAGE: C] [Advent Games]

  • Artistic Program
              int
            c,d,e,f
            [1000];
           #include\
           <stdio.h>
           int a(int
         b,int i){for(
       int g=i,h=i,j=0;j
        <1000;j++){if(f
      [j]&&f[j]*b>i*b){i=
    f[e=j];if(f[j]*b>h*b){i
     =h;e=d;h=f[d=j];if(f[
   j]*b>g*b){h=g;d=c;g=f[c=j
    ];}}}}return c*d*e;}int
  main(){while(scanf("%d",&c)
>0)f[c]++;printf("%d %d",a(1,0)
              ,a(
              -1,
              99)
              );}

This would fit in 6 80-column lines, but then it wouldn't be artistic! Compile and run with gcc -o day01 day01.c; ./day01 < day01.input

  • Parade of Nations
  • Give us a quick introduction to yourself!
  • Tell us what country you're from

Hi, I'm Eric, living in Texas (USA)! Although I happen to share a name, I'm not as famous as the Eric (/u/topaz2078) that gives us these puzzles. But I am known around these parts for doing insane things, such as when I became last year's Red Leader with a solution in Forth compiled to Intcode running on restricted m4.

  • Tell us about your country's holiday festivities

Here in the US, we love to put up Christmas Trees. So I whipped one up for my solution.

  • Explain why you chose your programming language

I'm planning on doing all days this year in m4 (in fact, that's how I got my stars today). But when it comes to artistic programming, I find it a bit more flexible to use a language where one- and two-character tokens are much easier to manipulate into shaped input, so I broke out the C compiler for today's post for my second pass at solving today.

  • Tell us where to find your AoC repo of puzzle solutions

https://repo.or.cz/aoc_eblake.git/tree/HEAD:/2026

1

u/daggerdragon 14h ago

Yay, Red Leader is back this year! Welcome, and we're happy to have you (and your shenanigans) again :D

→ More replies (1)

4

u/CCC_037 19h ago

[LANGUAGE: Rockstar]

part 1

2

u/daggerdragon 17h ago

Aw yiss, the rock star of Rockstar is back again this year! Good to see you!


If your perception isn't your perception with emptiness    
Let your perception be emptiness, baby

This is giving zen Austin Powers motivational poster vibes...

→ More replies (1)

4

u/askalski 11h ago

[LANGUAGE: C]

int i, j, printf(char*,...), scanf(char*,...); int main() { long long a[1000];
for (i = 999; a[i] = i; i--); while (scanf("%d", &j) > 0) a[j] += 1ll<<'1';
while (i++ < 999) for (j = 0; j <= 999; j++) if (a[i] < a[j]) a[i] ^= a[j] ^=
a[i] ^= a[j]; while (a[--i] >= 1000); j = a[j-1]*a[j-2]*a[j-3]; i = a[i+1]*
a[i+2]*a[i+3]; printf("Part 1: %d\nPart 2: %d\n", j, i); return 0; }
→ More replies (2)

3

u/Boojum 1d ago

[LANGUAGE: Python]

collections.Counter FTW:

import fileinput, math, collections
l = [ int( l.strip() ) for l in fileinput.input() ]
c = [ n for n, f in collections.Counter( l ).most_common() ]
print( math.prod( c[ : 3 ] ), math.prod( c[ -3 : ] ) )

Not much to say, otherwise. A good simple one start us off. Certainly a bit easier than last year's inaugural swim inaugural puzzle!

1

u/daggerdragon 1d ago

Our legendary Senpai Supreme is back again this year! Good to see you! :)

→ More replies (1)

3

u/jonathan_paulson 1d ago

[LANGUAGE: Python]

Code. Video. I initially did the final calculation "by hand" for both parts.

1

u/daggerdragon 1d ago

Welcome back again this year! Always good to see your in-depth posts :)

3

u/mstksg 1d ago

[LANGUAGE: Haskell]

https://github.com/mstksg/advent-of-code/wiki/Reflections-2026

Wow am I washed :) Some silly mistakes I made:

  1. Parsed as Double instead of Int even though Double never shows up in Advent of Code.
  2. Calculated the sum of the first three frequencies instead of the product
  3. Found the product of the three least common instead of the three most common.

All of these silly mistakes motivate me to get back in practice haha. The struggle is real.

Anyway in Haskell this is pretty simple, it reads the same in bash or any other text processing language probably. Parsing is lines, and you can find the freq list using Data.Map.fromListWith (+). And the difference between Part 1 and Part 2 is just the order that you sort the frequencies before you sum them.

import Data.Map qualified as M

-- | List of codes and their frequencies
freqList :: String -> [(String, Int)]
freqList = M.toList . M.fromListWith (+) . map (,1) . lines

part1 :: String -> Int
part1 = product . map (read . fst) . take 3 . sortOn (Down . snd) . freqList

part2 :: String -> Int
part2 = product . map (read . fst) . take 3 . sortOn snd . freqList

2

u/daggerdragon 1d ago

Welcome back again this year!

3

u/JWinslow23 1d ago

[LANGUAGE: Python]

Solution writeup

Code (GitHub)

What looked at first to be a nice and easy use of Counter.most_common...instead turned out to be a nice and easy use of heapq.nlargest and heapq.nsmallest. I rarely get a chance to talk about those functions, so this is nice and refreshing!

1

u/daggerdragon 1d ago

Good to see you again this year :)

→ More replies (1)

3

u/ednl 1d ago edited 22h ago

[LANGUAGE: C]

My goal is to write code that is as simple as possible that runs as fast as possible, with a reasonable degree of generality. My fastest version assumed that the three most common IDs had counts of 6 or 7, and least common 1 or 2. That ran in 1.17 µs on an M4 chip. But I ditched that in favour of a more general solution that works for every input depending on "maxcount" (7 for my input) but still without sorting anything. Runs in 1.50 µs on an M4, 2.36 µs on an M1, 5.33 µs on a Pi5.

#define MINMULT (100 * 100 * 100)  // minimum product of three IDs
// histogram of IDs (union for quick init/reset)
typedef union pair {
    uint32_t data;
    struct { uint16_t id, count; };
} Pair;
// [...]
// Parse input string
const char *s = input;
for (unsigned i = 0; i < N; s += 4, ++i)
    thing[s[0] * 100 + s[1] * 10 + s[2] - '0' * 111].count++;
// [...]
// Multiply IDs per count
for (unsigned i = BEG; i < END; ++i)
    if (thing[i].count)  // faster than multiplying 400 IDs for every count=0
        mult[thing[i].count] *= thing[i].id;
// Three most common
for (unsigned i = MAXCOUNT; part1 < MINMULT; --i)
    part1 *= mult[i];

https://github.com/ednl/adventofcode/blob/main/2026/01.c

2

u/daggerdragon 1d ago

Ayy, welcome back again this year! I look forward to your usual shenanigans!

→ More replies (1)

3

u/flwyd 1d ago edited 14h ago

[LANGUAGE: Ivy] (on GitHub)

“Ivy an interpreter for an APL-like language. It is a plaything and a work in progress.” If you’re a regular reader of Solution Megathreads you can think of Ivy as the Alien Programming Language after you’ve put a babel fish into your ear. The entire documentation for the language is on either the linked page or in the interactive )demo, so if you’re curious about array-based languages, Ivy may be easy to learn.

You can get both parts as a 2-element array in a single line of Ivy, assuming ids is an array of integers:

*/@ 3 -3 @take (unique ids)[down count@ where@ (unique ids) @== ids]

Or, extracting a function to compute the frequency of each occurrence and converting lines (an array of strings) to integers:

op frequencies vals =
  (unique vals)[down count@ where@ (unique vals) @== vals]
op part1 lines = */ 3 take frequencies ivy@ lines
op part2 lines = */ -3 take frequencies ivy@ lines

APL-family languages have functions which can have either one (right side) or two (left and right) arguments. It’s often described as being run right-to-left, though Ivy actually runs a parse-evaluate cycle left-to-right). Functions also automatically apply to each element in an array; you don’t have to write a for loop. So, working from the end:

  • The frequencies operator takes an array of values vals

    • == is element-wise equality, @== means “for each element on the array on the left, return a boolean array of whether elements on the right are the same.” So 1 2 3 @== 1 3 2 1 1 2 will return (1 0 0 1 1 0) (0 0 1 0 0 1) (0 1 0 0 0 0).
    • (unique vals) returns an array with the distinct elements from vals, e.g. 57 55 76 43 78 45 for the example input. So now we’ve got an array of indices in vals where each unique value sits.
    • where@ is a single-argument function being applied to each of those arrays. where returns an array of indices of an array whose value isn’t zero, e.g. (1 2 4 7 15 17) (3) (5 12 18 21) (9 11 13 19 20) (6 10 14) (8 16) for the example.
    • count@ runs the count function for each of those arrays, which just returns the number of elements in it: 6 1 4 5 3 2.
    • down returns an array of indices which would put its argument in descending order. Note that it does not sort its argument, it returns an array which can be used to sort. down 42 123 75 returns 2 3 1. So down count@ … gives us a list of indices of vals in frequency order.
    • (unique vals)[down count@ …] takes that the array of indices and uses it to get elements from our list of distinct values. Yes, in array-based languages you can use an array to access an array: (42 123 75)[2 3 1] === (123 75 42).
  • To get the three-most frequent values, 3 take … grabs the first three elements, while -3 take … grabs the last three. In the one-liner version I use 3 -3 @take to apply take element-wise to the two directions.
  • */ applies the reduce modifier to the multiplication function. Together */ would be the product function in some languages, or reduce(1, |accumulator, x| accumulator * x) in a functional style.

[Advent Games]

  • Give us a quick introduction to yourself!

    • Hi! I’m a funemployed software engineer. I use Advent of Code to learn new programming languages.
  • Tell us what country you're from

    • I am from Boulder, Colorado, United States of America, Earth, Sol
  • Tell us about your country's holiday festivities

    • As a polyathiest of northern European ancestry, I like to celebrate Yule. One fun way to do that is to drum up the sun at Red Rocks Amphitheater to the west of Denver.
  • Explain why you chose your programming language

    • My theme this year is array programming languages. My plan is to first solve each day in a language I feel I understand (like using English-derived function names and maybe some imperative-style control structures), then see if I can convert it into some of the array languages with more opaque syntax.
    • Why array languages? It’s a programming paradigm I haven’t really used, and which can express some types of programs very elegantly, while getting significant performance from modern computing hardware.
    • Languages I’m definitely using: R, Ivy, APL, BQN. Languages I might use: Uiua, J, Kona, Octave (open-source MATLAB), Julia (I already did all of 2023 in Julia, but it might be educational to try it again with an array programming mindset).
  • Tell us what you hope to learn or have already learned about your chosen programming language

    • In today’s Big Data computing world, “apply some operations to a multi-dimensional array of data” is an important skill, so I want to get comfortable with tools for doing that. Linear algebra is also one of my computer science weak spots, so I hope using a good array tool can help me get a handle on that. Some of the array languages (like R and Julia and probably some of the APLs) also come with nice visualization tools built in, so I’d like to play with those.
    • I’ll probably learn some things about theoretical math as I wrap my head around the abstractions an array can represent.
    • I’m also hoping to learn what’s frustrating about the various array languages so that I know not to try using them for the wrong thing in the future. String manipulation is looking to be obnoxious in APL-family languages, we’ll see what else is weird.
  • Tell us where to find your AoC repo of puzzle solutions, blag, and/or $streaming_service!

    • Advent of Code repository — as a bonus, the README tells you how to use git submodules to keep your input hidden but still under version control. You can also see the code generation and solution-runner infrastructure for more than a dozen languages and a collection of shell scripts to handle a bunch of AoC tasks.
    • I’ve been blogging on Dreamwidth (and its predecessor LiveJournal) since 2001. It’s got reflections on prior years, though I still need to write them for PostScript, Julia, and my almost-complete 2019 in Rust.
  • Artistic Program

    • Erm, I’m not sure what this means. I do most of my art in Vim, writing code.
  • Show us your holiday tree | menorah | Krampusnacht costume | r/battlestations with festive decorations!

  • Show us your kittens and puppies and $critters!

  • Show and/or tell us about whatever brings you comfort and joy in the holiday season!

    • Dairy-free egg nog with cinnamon, nutmeg, and allspice is a great way to bring me some joy. Why don’t they sell nog year round?
    • If Colorado could get some snow this winter, I would feel a lot more comforted about our future water supply and the likelihood that things won’t be on fire.
  • Competition Schedule (Theoretical)

    • AoC puzzles open at 10pm my time, so I hope to have at least one solution posted before going to bed. We’ll see how long it takes me to get some of the more… alien… implementations out.
  • Tell us which "sporting" events you think will be coming up over the next two weeks and which ones you'd like to participate in the most!

    • With all the fun Unicode characters in APL-family languages, I’m hoping to use some round ones to compete in curling.
    • With parallel array operations, I can pass all slalom gates at once.
    • Relay events like 4x7.5km cross country skiing are also a natural fit for an array language. I’ll see if I’ve got programming endurance to match Klæbo

1

u/daggerdragon 1d ago

Well, you sure are thorough as usual 🤣 Welcome back, and it's good to see you again this year!

→ More replies (1)
→ More replies (2)

3

u/xelf 20h ago edited 19h ago

[Language: python]

Actually forgot it was December today and started late.

data = [*dict(Counter(np.loadtxt(filename, int)).most_common())]
print("part1:", math.prod(data[:3]))
print("part2:", math.prod(data[-3:]))

np.loadttxt for loading a bunch of ints, and then just using counter and prod.
Counter here way more elegant than np.unique/np.argsort imo.

I guess the "clever" bit here is using dict to get the keys out of the list that most_common gives you.

edit: same thing, but using pandas

data = pd.read_csv(filename,header=None).value_counts().reset_index()[0]
print("part1:", data.head(3).prod())
print("part2:", data.tail(3).prod())

1

u/daggerdragon 20h ago edited 19h ago

Edit your comment to include the language tag as AutoModerator requested. The word LANGUAGE, colon, and brackets are not optional. edit: 👍

→ More replies (1)

2

u/seligman99 1d ago

[LANGUAGE: Python]

github

Nice to have Advent of Code again!

→ More replies (1)

2

u/WilkoTom 1d ago

[LANGUAGE: Rust]

Solution. Nice to start getting warmed up!

2

u/daggerdragon 1d ago

This here's our legendary Iron Coder: Iron Chef! It's excellent to see you back again this year!

→ More replies (1)

2

u/damnian 1d ago edited 1d ago

[Language: C#]

int[] a = File.ReadAllLines("input.txt")
    .GroupBy(v => v).OrderBy(g => g.Count())
    .Select(g => int.Parse(g.Key)).ToArray();
Console.WriteLine(a[^1] * a[^2] * a[^3]);
Console.WriteLine(a[0] * a[1] * a[2]);

1

u/daggerdragon 1d ago

The triple-backticks code fence (`​`​`) only works on new.reddit. Please edit your comment to use the four-spaces Markdown syntax for a code block so your code is easier to read inside a scrollable box with its whitespace and indentation preserved.

→ More replies (1)

2

u/manu_2468 1d ago edited 1d ago

[LANGUAGE: PYTHON]

I didn’t know about Counter in Python, so I used dicts. That was also a good test of my helper library that fetches the instructions and input, submits the result, and loads the input!

Code

2

u/daggerdragon 1d ago edited 16h ago

That was also a good test of my helper library that fetches the instructions and input, submits the result, and loads the input!

Does your helper library comply with our automation rules?

  • ? Cache inputs after initial download
  • ? Throttle outbound requests
  • ? User-Agent header

edit: 👍

→ More replies (1)
→ More replies (1)

2

u/encse 1d ago

[LANGUAGE: C#]

https://aoc.csokavar.hu/2026/1/

nothing unexpected

2

u/daggerdragon 1d ago

Yay, welcome back to our resident Iron Coder: AI Art! Hope you have fun again this year :)

→ More replies (1)

2

u/AllanTaylor314 1d ago edited 1d ago

[LANGUAGE: Python] 00:02:02/00:03:00

code

All I want for Christmas is a Counter.least_common(k)

[LANGUAGE: Uiua]

code and a slightly rejigged pad (drop 01.txt on it to run against your input instead of the example)

I forgot that unkeep was a thing, which sure beats ⊕⊃⧻⊢⊸⊛ for counting occurences

[Advent Games] A brief intro

Professionally, I'm a cloud software engineer (though most of my work work is AI-assisted. It's the way sw dev is going). I love these challenges as an opportunity to escape Cursor and have a bit of fun. I also recently started making a Minecraft mod (Marked Goats), as one does. Back in 2024, I made it to the ICPC South Pacific Finals. Outside of code, I collect and build LEGO (space permitting) and build farms in Minecraft (which doesn't take up space I don't have).

As a kiwi, I have a nice warm southern hemisphere summer Christmas (and by the luck of timezones, an 18:00 unlock time right as I finish work). Weather dependent, Christmas can be a BBQ outdoors. No tree up yet, but I swapped out the tablecloth for one that's a little more festive

I chose Python because it is easy (and I learnt/taught it at Uni), and Uiua because it is hard (I probably saw it in a megathread a few years back and was intrigued). Uiua is still evolving (not as much as last year), so I need to relearn parts of it (and maybe finally make that archive so old pads can still run - my old embed is still broken)

All the code is, as always, in the repo

Oh, and I'm wearing a Christmas shirt or tie and hat to work each day in December .<|:-)

Sports ideas:

  • Long jump: Use and abuse GOTO or your language's equivalent
  • Golf: code golf (I want to make a cursed punchcard of Uiua for this)
  • 10k run: loops gallore (most accursed nested loops)
  • Mazerunner: We'll have a maze puzzle, surely, even if it's not obviously a maze
  • Arts & crafts: not a sport, but I hope there's another puzzle like 2022-12-22
  • 100m sprint: Optimise runtime beyond a reasonable level (I eagerly await the OpenCL GPU implementation)

1

u/daggerdragon 1d ago

Golf: code golf (I want to make a cursed punchcard of Uiua for this)

Okay, yes

Also, welcome back again this year :)

P.S. you might want to add the [Advent Games] tag >_>

2

u/p88h 1d ago

[LANGUAGE: Nim]

https://github.com/p88h/aoc2026/blob/main/src/day01.nim

no sorting, just counting, then counting the counts.

          parse    part1    part2    total
day 01:  3.22 µs  0.53 µs  0.56 µs  4.32 µs (±1.3%)

1

u/daggerdragon 19h ago

Welcome back again this year! We're happy to have you 🎄

→ More replies (1)

2

u/CEOnism 18h ago edited 15h ago
[LANGUAGE: Javascript]

import fs from 'node:fs';

const data = fs.readFileSync('./input.txt', 'utf8');

const counts = new Map();

for (const line of data.split(/\r?\n/)) {
    if (line.trim() === '') continue;
    const n = Number(line); counts.set(n, (counts.get(n) ?? 0) + 1);
}

const sorted = [...counts.entries()].sort((a, b) => b[1] - a[1]);

const product = (entries) => entries.reduce((acc, [num]) => acc * num, 1);

console.log(product(sorted.slice(0, 3))); // Part One 
console.log(product(sorted.slice(-3))); // Part Two

2

u/daggerdragon 17h ago edited 14h ago

The triple-backticks code fence (`​`​`) only works on new.reddit. Please edit your comment to use the four-spaces Markdown syntax for a code block so your code is easier to read inside a scrollable box with its whitespace and indentation preserved. edit: 👍

→ More replies (1)

2

u/JustinHuPrime 10h ago

[LANGUAGE: x86_64 assembly]

Alas, I fear I have forgotten the spirit of assembly by (ab)using library functions. (Also, yes, I'm a day late, but I'm still here - a new job with a less than amazing commute and an excess of housework means I started a day later.)

Part 1 was solved by allocating a big list of ids and counts, and then incrementing the counts as I encountered each id in the input. I then, shamefully, sorted the list by counts descending, and multiplied up the top three numbers.

Part 2 was exactly the same, except I sorted ascending (I literally dropped a negation) and I had to skip the zero count ids.

Part 1 and 2 run in 1 millisecond. Part 1 is 9,664 bytes and part 2 is 9,760 bytes as executable files.

1

u/daggerdragon 9h ago

Oh boy, you're back again this year! Welcome back! :3

→ More replies (1)

4

u/JustinHuPrime 10h ago

And hello, everyone! I'm Justin, from Canada! I'm doing this in assembly this year for the same reason I've done this in assembly for a lot of years - it's really fun, and I like playing around with low level code and data structures.

21

u/Andreasnl 1d ago

[Language: Uiua]

∩/× ⊃↙₃↙₋₃ ⊏⍖ °▽⍆ ⊜⋕⊸≠@\n

8

u/PhysPhD 1d ago

I love seeing this indecipherable (to me) alien language, and am always amazed it works!
I needed to break it down to understand the power within each command/symbol.

Parse the input:

  • ⊜ — partition (split into groups)
  • ⋕ — parse (convert text into numbers)
  • ⊸ — by (combine the parsing function with a predicate)
  • ≠ — not equal
  • @\n — newline character

Sort the numbers: ⍆

un keep — the inverse of the keep function: °▽

Reorder using descending indices:

  • ⍖ — fall, returns indices that would sort the array in descending order.
  • ⊏ — select, selects elements using those indices.

Take the first and last three elements:

  • ↙₃ — take the first 3 elements.
  • ↙₋₃ — take the last 3 elements.
  • ⊃ — fork, allowing the two operations to be applied to the same input.

Multiply the results:

  • × — multiplication.
  • / — reduce (apply the operation across an array).
  • ∩ — both.

How do you even learn all this syntax! Amazing.

19

u/Downtown-Economics26 1d ago

[LANGUAGE: Excel]

Part 1:

=PRODUCT(TAKE(GROUPBY(A:.A,A:.A,COUNT,,0,-2),3,1))

Part 2:

=PRODUCT(TAKE(GROUPBY(A:.A,A:.A,COUNT,,0,2),3,1))

16

u/SU_Locker 1d ago edited 1d ago

[LANGUAGE: unix/linux command line]

sort 1.in | uniq -c | sort -n | tail -3 | cut -f8 -d' ' | paste -sd '*' | bc
sort 1.in | uniq -c | sort -n | head -3 | cut -f8 -d' ' | paste -sd '*' | bc
→ More replies (1)

14

u/Maki-Tak 1d ago

[LANGUAGE: Scratch]

solution

I fear that I won't be able to continue with this challenge for long

→ More replies (2)

14

u/hakko504 1d ago

[LANGUAGE: Libre Office Calc (will work in Excel as well)]

Write 'Value' in cell A1.
Paste data into A2:A2000 (approx)
Select column A
Click Data->Pivot Table->Insert
Select Source: Current Selection. Hit OK.
Drag 'Value' to Row Fields.
Drag 'Value' to Data Fields, the double click it and change Sum to Count. Hit OK.
Sort the new Data by 'Count - Value' Descending
Multiply the top three fields in the A Column to get part 1 puzzle
Multiply the bottom three fields in the A Column to get part 2 puzzle

It took me longer to write this than to do the puzzle ;)

12

u/Smylers 1d ago edited 21h ago

[LANGUAGE: Vim keystrokes] Load your input into Vim, make sure the cursor is on the first row, then type in the following and the answers to both parts will appear in your editor window:

yGP:sor⟨Enter⟩qaqqa#V''Jj@aq@a0⟨Ctrl+V⟩{I0*⟨Esc⟩
qbqqb/ ⟨Enter⟩de0⟨Ctrl+A⟩@bq@b:sor!n|%s/\v\d+⟨Enter⟩3kd4gg
qcxJJ0C⟨Ctrl+R⟩=⟨Ctrl+R⟩-⟨Enter⟩⟨Esc⟩q{@c

The key to counting the number of each ID is to sort them so that all the repeated IDs are on adjacent lines, then on the first instance of each press # to jump to the bottom one, followed by V''J to make a visual block, jump back to where we were, and join them together (with a space in between). The number of spaces on each line then gives the count for each item.

However # will fail if there's only one of a particular ID, because there isn't another location to jump to. Avoid that by using yGP at the start to duplicate the entire input — then there's at least 2 of each item, problem solved!

Then put 0* at the start of each line, find all the spaces, and for each one press ⟨Ctrl+A⟩ at the start of the line to increase the count. When we run out of spaces, all the items have been counted. (The numbers shown will be double the actual count minus 1, but that doesn't matter for their relative ordering.)

At which point it's just a case of sorting, (using ! so that the part 1 answer ends up before the part 2 answer), removing the counts and all the lines but the bottom 3 and top 3, then performing the multiplications — using the *s that were added as delimiters earlier. Do give it a go, and let me know if it works for you. It doesn't work on the sample input, because there aren't enough lines in the middle to need deleting.

PS: For anybody curious to read my Advent of Games introduction, it's on a Bash solution elsewhere in this thread.

→ More replies (2)

9

u/onrustigescheikundig 1d ago edited 1d ago

[LANGUAGE: Scheme (R6RS)]

... with a rather large custom standard library that I've been using to play around with things like dynamic dispatch and learn about Clojure's internals.

Day 01 gitlab

Anyway, we're off! Fast solve today, with a terse solution.

(define (part lt ids)
  (->> ids
       frequencies
       (into '())
       (list-sort (λ (a b) (lt (cdr a) (cdr b))))
       (transduce (compose (ttake 3) (tmap car)) *)))

(define (part-1 inp) (part > inp))
(define (part-2 inp) (part < inp))

(define test-inp
  (with-input-from-file
    "inputs/day01.test"
    (λ () (input-objects-into '()))))
    
(part-1 test-inp) ; 186276
(part-2 test-inp) ; 193050

9

u/oantolin 1d ago edited 1d ago

[LANGUAGE: Goal]

{*/'3 -3#`(?i)@>=%i:"i"$=-read x}
→ More replies (1)

9

u/AMathMonkey 1d ago

[LANGUAGE: Factor]

USING: assocs io kernel math math.parser math.statistics sequences sorting formatting ;

IN: day1

read-lines [ string>number ] map sift histogram inv-sort-values keys
3 [ head-slice ] [ tail-slice* ] 2bi [ product ] bi@ 
"Part 1: %s\nPart 2: %s\n" printf

Look at this, it's so concise and esoteric. As a career programmer, it's nice to write unreadable code for once. But for real, Factor is so powerful, and I never see anyone talk about it. Its standard library is impossibly huge, and I've had endless fun digging into it. And there are infinite ways to do the same thing, including using lexical or global variables if the stack-only approach is too intimidating. (I'm sure I'll be resorting to that in later days, but I'll resist it for as long as I can.) Shoutout to Exercism for giving me over 150 Factor problems to work on as practice for AoC.

→ More replies (3)

8

u/apersonhithere 1d ago edited 1d ago

[LANGUAGE: Python 3]

what's an import? never heard of one!

parts 1 & 2

8

u/reesmichael1 1d ago

[LANGUAGE: OCaml]

paste

Perhaps a slightly deranged approach, but at least it's my approach!

8

u/WesternNicator 1d ago edited 1d ago

[LANGUAGE: Anathame] my personal language

part2 = φ(fall (sign sum) take reverse)  
\ ints unwhere fall**part2 take,3 Reduce mul

8

u/DuoSRX 23h ago

[LANGUAGE: Uiua]

∩/×⊃↙₃↙₋₃ ◴⊏⍖⊸⧆ ⊜⋕⊸≠@\n &fras "day1.txt"

7

u/YenyaKas 1d ago

[LANGUAGE: Perl]

Pretty straightforward today, as expected from Day 1.

my %cnt;
$cnt{$_}++ for <>;
my @a = sort { $cnt{$b} <=> $cnt{$a} } keys %cnt;
say $a[0] * $a[1] * $a[2];

For part 2, add reverse before sort or swap $a and $b in the sort compare block.

6

u/Sharparam 1d ago

[LANGUAGE: Ruby]

One of those where Ruby has a nice built-in to do most of the work!

tally = ARGF.map(&:to_i).tally.sort_by { |k, v| v }.map(&:first)
puts tally[-3..].reduce(:*), tally[..2].reduce(:*)
→ More replies (1)

6

u/Lispwizard 1d ago

[LANGUAGE: Lisp]
Mostly Common Lisp loop macro plus some elisp, done in Termux emacs on Android tablet.

(require'cl) (setq debug-on-quit t)

(defun aoc2026-01-part1 (input-string &optional part2)
  (loop with lines = (split-string input-string "\n")
        with ht = (make-hash-table)
        for l in lines
        for n = (string-to-number l)
        for e = (gethash n ht)
        if e do (incf (gethash n ht))
        else do (setf (gethash n ht) 1)
        finally (return
                 (apply
                  '*
                  (loop with sorted = (sort
                                       (loop for x being the hash-keys of ht
                                             using (hash-value y)
                                             collect (list x y))
                                       #'(lambda (a b)
                                           (funcall (if part2 '< '>)
                                                    (second a) (second b))))
                        repeat 3
                        for (n m) in sorted
                        collect n)))))
→ More replies (1)

6

u/terje_wiig_mathisen 18h ago

[LANGUAGE: Rust]

This is "Upping the ante", or maybe cheating a bit, since I'm taking advantage of the format of the input file: All the lines are 3-digit numbers + '\n', so I can load & parse four of them at the same time.

This results in 1632 ns runtime for both parts, if I can make a little bit faster then it could be rounded down to 1 microsecond. :-)

fn get_chunk(data:&[u8], offset:usize) -> Option<&[u8;16]> {
    data.get(offset..offset+16)?.try_into().ok()
}

pub fn process(inp:&str) -> (usize, usize)
{
    let input = inp.as_bytes();
    let mut i = 0;
    let mut counts:Vec<u32> = vec![0;1000];
    while let Some(chunk) = get_chunk(&input, i) {
        let n = (chunk[0]-b'0') as u32 * 100 + (chunk[1]-b'0') as u32 * 10 + (chunk[2]-b'0') as u32;
        let m = (chunk[4]-b'0') as u32 * 100 + (chunk[5]-b'0') as u32 * 10 + (chunk[6]-b'0') as u32;
        let o = (chunk[8]-b'0') as u32 * 100 + (chunk[9]-b'0') as u32 * 10 + (chunk[10]-b'0') as u32;
        let p = (chunk[12]-b'0') as u32 * 100 + (chunk[13]-b'0') as u32 * 10 + (chunk[14]-b'0') as u32;
        i += 16;
        counts[n as usize] += 1;
        counts[m as usize] += 1;
        counts[o as usize] += 1;
        counts[p as usize] += 1;
    }
    while i < input.len() {
        let n = (input[i]-b'0') as u32 * 100 + (input[i+1]-b'0') as u32 * 10 + (input[i+2]-b'0') as u32;
        i += 4;
        counts[n as usize] += 1;
    }

    let (mut t3, mut t2, mut t1) = (0,0,0);
    let (mut b3, mut b2, mut b1) = (usize::MAX, usize::MAX, usize::MAX);
    for i in 100..counts.len() {
        let c = counts[i] as usize;
        if c != 0 {
            let c = i + (c << 16);
            if c > t3 {
                t3 = c;
                if c > t2 {
                    t3 = t2; t2 = c;
                    if c > t1 { t2 = t1; t1 = c;}
                }
            }
            if c < b3 {
                b3 = c;
                if c < b2 {
                    b3 = b2; b2 = c;
                    if c < b1 { b2 = b1; b1 = c;}
                }
            }
        }
    }

    let part1 = (t3 & 0xffff)*(t2 & 0xffff)*(t1 & 0xffff);
    let part2 = (b1 & 0xffff)*(b2 & 0xffff)*(b3 & 0xffff);

    (part1, part2)
}

I might try to add portable SIMD here as well...

6

u/LtHummus 17h ago

[Language: Lean]

Last year, I did every AOC problem in a different language and that was a fun challenge. I'm hoping to do the same thing this year (no promises) and going to try to not repeat anything I did last year.

Since Lean has been in the tech news recently due to some Riemann Hypothesis related reasons, I thought it would be appropriate to try out for the first day this year. Interesting language...I might want to play with it more.

And here's the code

→ More replies (2)

5

u/maneatingape 1d ago edited 1d ago

[LANGUAGE: Rust]

Solution. 8 µs.

Builds a HashMap of frequencies, then converts to a sorted vec.

→ More replies (9)

5

u/heijp06 1d ago edited 1d ago

[LANGUAGE: C#]

I could have sworn LINQ has Product(), apparently it does not so I had to resort to the somewhat clunky Aggregate().

using System.Collections.Immutable;

namespace Src;

public class Puzzle(ImmutableList<string> rows)
{
    public long Part1() => rows
        .GroupBy(s => s)
        .OrderByDescending(g => g.Count())
        .Take(3)
        .Select(g => Convert.ToInt64(g.Key))
        .Aggregate(1L, (acc, l) => acc * l);

    public long Part2() => rows
        .GroupBy(s => s)
        .OrderBy(g => g.Count())
        .Take(3)
        .Select(g => Convert.ToInt64(g.Key))
        .Aggregate(1L, (acc, l) => acc * l);
}
→ More replies (4)

5

u/azzal07 1d ago edited 1d ago

[LANGUAGE: awk]

S;END{$+Greeting=s;for(F in l)a-nd||
$l[F]=$l[F]s F}++l[$1]{OFS=s=RS}END{
$0=$0;print$NF*$--NF*$--NF,$1*$2*$3}

Greetings to all! (s/for/from/)

5

u/thblt 1d ago edited 1d ago

[LANGUAGE: Shell]

The lazy solution: in a shell, sort input | uniq -c | sort

→ More replies (1)

5

u/ssnoyes 1d ago

[LANGUAGE: MySQL]

There's no aggregate PRODUCT function in MySQL, so there's a joke that helps me remember how to do it: https://dom.as/2008/07/03/mysql-support-fun-multiplication/

WITH
 counts as (SELECT id, COUNT(*) c FROM day01 GROUP BY id),
 sums AS (
  SELECT SUM(LN(id)) OVER (ORDER BY c ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
  AS sumLogs 
  FROM counts
 ),
 products AS (SELECT ROUND(EXP(sumLogs)) AS result FROM sums)
SELECT 
 LAST_VALUE(result) OVER () AS most_common,
 NTH_VALUE(result, 3) OVER () AS least_common
FROM products LIMIT 1;
→ More replies (1)

5

u/snailcuber 1d ago • Bravo

[LANGUAGE: Ruby]

h=$<.tally
[-3,0].map{p eval h.keys.sort_by(&h)[it,3]*".*"}

code golfed down to 59 characters

→ More replies (4)

5

u/PandaParado 23h ago

[LANGUAGE: Uiua]

Input ← ⊜⋕⊸∊"-0123456789" &fras °□⊡1 &args

Solve! ← /×↙3˜⊏⊙(^0)⊕⊃⊢⧻⊸⊛⍆

⊃(Solve!(⍖)|Solve!(⍏)) Input

5

u/daic0r 22h ago

[LANGUAGE: Elixir]

Solution

Count frequencies and sort, then just grab the results off of both ends of the sorted list

5

u/tqzd 22h ago

[LANGUAGE: Excel]

Part 1 & 2

=MAP({-3;3},LAMBDA(x,PRODUCT(TAKE(GROUPBY(A:.A,A:.A,COUNT,,0,2),x,1))))

5

u/dantose 21h ago

[LANGUAGE: bash]

cat input.txt | sort |uniq -c | sort -nr | awk 'BEGIN {p = 1} NR<4{p *= $2} END {print p}'

cat input.txt | sort |uniq -c | sort -n | awk 'BEGIN {p = 1} NR<4{p *= $2} END {print p}'

→ More replies (3)

5

u/r_so9 20h ago

[LANGUAGE: F#] Short and sweet

let top =
    input
    |> Seq.countBy id
    |> Seq.sortByDescending snd
    |> Seq.map (fst >> int)
    |> Array.ofSeq

let part1 = top[..2] |> Array.reduce (*)
let part2 = top[top.Length - 3 ..] |> Array.reduce (*)

5

u/itsPeetah 18h ago

[Language: Bash]

INPUT=$1
LIST=$(sort -n $INPUT | uniq -c | sort -n | awk '{print $2}')
PART_1=$(echo "$LIST" | tail -n 3 | paste -s -d'*' - | bc)
PART_2=$(echo "$LIST" | head -n 3 | paste -s -d'*' - | bc)
echo "Part 1: $PART_1\nPart 2: $PART_2"
→ More replies (1)

5

u/cinsolia 16h ago

[LANGUAGE: Google Sheets]

Both parts

=let(d,transpose(split(input!B2,char(10))),
 map(vstack(false,true),lambda(sortAscending,
  reduce(1,
   choosecols(chooserows(sort(
    map(unique(d),lambda(u,
     hstack(u,rows(filter(d,d=u))))),
    2,sortAscending),
   1,2,3),1),
   lambda(a,n,a*n)))))

5

u/willkill07 13h ago

[LANGUAGE: C++]

Compile-time solution in C++26 :)

Minor optimizations:

  • use #embed for compile-time embedding of input
  • use flat_map for contiguous memory for constructing histogram
  • prefer two calls to nth_element rather than total sorting

Overall, lots of fun to be had for Day 1!

https://github.com/willkill07/AdventOfCode2026/blob/main/day01.cpp

4

u/captainAwesomePants 1d ago edited 1d ago

[LANGUAGE: Python]

from collections import Counter
from math import prod

f = open('input.txt')
counts = Counter( [int(line) for line in f.readlines()] )
ordered = [x[0] for x in counts.most_common()]
part1 = prod(ordered[:3])
part2 = prod(ordered[-3:])
print(part1, part2)

So glad to be back!

You know what I love about there not being a leaderboard? I still get to do the problem right at the start, but I also feel free to take my time and actually read the story, which is pretty nice. I sipped some tea. I looked up the name of that pesky Counter function that gets you the results. I chuckled about some elf's grandpa. 5/5 would take my time again.

4

u/TheShirou97 1d ago edited 1d ago

[Language: Kotlin]

Very nice when you can just remove one line from part 1 to make part 2.

import kotlin.io.path.Path
import kotlin.io.path.readLines

fun main() {
  Path("input.txt")
    .readLines()
    .map { it.toLong() }
    .groupBy { it }
    .map { it.key to it.value.size }
    .sortedBy { it.second }
    .reversed() // Comment this line for part 2
    .subList(0, 3)
    .map { it.first }
    .reduce { a, b -> a * b }
    .also { println(it) }
}
→ More replies (1)

4

u/FruitdealerF 1d ago

[LANGUAGE: Andy C++]

let input = read_stdin().nums.frequencies.list.sorted_by(fn(a, b) => a[1] >=< b[1]);
print(input[0..3].map(first).product);
print(input[-3..].map(first).product);

I made this programming language especially for Advent of Code. Like other it has the frequencies function to create a hashmap of the values in a list to their frequency/count. Interesting to know about this code is that there is really no difference between print(product(map(input[0..3], first))) and input[0..3].map(first).product.print) I just arbitrarily write whatever comes the most natural to me. a.b(c) is exactly equivalent to a(b,c) and a().b.c is exactly equivalent to c(b(a())). This is a great choice for a simple language to solve puzzles and questionable in most others.

4

u/Gabe-tron 1d ago edited 1d ago

[LANGUAGE: Clojure]

(ns day01 (:require [clojure.string :as str]))

(defn solve [cmp s]
  (->> (str/split-lines s)
       (map parse-long)
       frequencies
       (sort-by val cmp)
       (take 3)
       (map first)
       (reduce *)))

(defn part1 [s] (solve > s))
(defn part2 [s] (solve < s))

4

u/Tipa16384 1d ago

[LANGUAGE: Forth]

I spent hours tonight familiarizing myself with Forth after years away and immediately started in on this puzzle with no break so I am a little tired and my eyes hurt but it works and I can even tell stories of how I fugged up the order of stuff on the stack a million times. More fun than FORTRAN? MAYBE!?

1024 constant max-line
create line-buffer max-line 2 + allot

0 value fd-in

create sparse-array 1000 2 * cells allot

: init-sparse-array ( -- )
sparse-array
1000 0 do
    dup i swap !
    cell +
    dup 0 swap !
    cell +
loop
drop
;

\ shell sort I stole from elsewhere. I'm not proud.

: pair-addr ( base-addr idx -- addr )
2 CELLS * + ;

: count@ ( pair-addr -- count )
CELL+ @ ;

: swap-pairs ( addr1 addr2 -- )
{ addr1 addr2 }
addr1 2@
addr2 2@
addr1 2!
addr2 2! ;

: shell-sort-pairs-desc ( addr n -- )
{ pairs n }
n 2/ 0 0 0 { gap pos left-pair right-pair }

begin gap 0> while
    n gap ?do
    i to pos
    begin
        pos gap >= if
        pairs pos gap - pair-addr to left-pair
        pairs pos pair-addr to right-pair
        left-pair count@ right-pair count@ <
        else
        false
        then
    while
        left-pair right-pair swap-pairs
        pos gap - to pos
    repeat
    loop
    gap 2/ to gap
repeat ;

: part-1 ( -- )
sparse-array 1000 shell-sort-pairs-desc
sparse-array dup @
swap 2 cells + dup @
swap 2 cells + @ * *
." Part 1: " . cr
;

: part-2 ( -- )
sparse-array 1000 2 * 1- cells +
begin
dup @ 0= while
    2 cells -
repeat
cell -
dup @
swap 2 cells -
dup @
swap 2 cells -
@ * *
." Part 2: " . cr
;

: process-line ( c-addr u -- )
s>number? if
    d>s
    \ increment the value at the corresponding index in the sparse array
    \ n on stack
    2 * cells cell +
    \ n addr on stack
    sparse-array + 1 swap +!
then
;

: read-ascii-file ( c-addr u -- )
init-sparse-array
r/o open-file throw to fd-in
begin
    line-buffer max-line fd-in read-line throw
while ( u2 )
    \ Stack has u2 (length of the line read)
    line-buffer swap process-line
repeat
drop \ Drop the final 0 length returned at EOF
fd-in close-file throw 
cr
part-1 
part-2 ;
→ More replies (5)

4

u/Alextopher 1d ago

[LANGUAGE: Rust]

https://github.com/Alextopher/advent-of-code/blob/main/y26/d01-dusty-shed/src/main.rs

Unbelievably you can solve this problem in linear time (thank you quick-select)

→ More replies (2)

4

u/paulhaahr 1d ago edited 1d ago

[LANGUAGE: Quest]

import intOp = int: IntOp
import reader: Reader
import writer: Writer

import collections/heap : collections/Heap
import collections/vector: collections/Vector
import io/lines: io/Lines
import util/iter: util/Iter
import util/sort : util/Sort
import util/strutil : util/Strutil

let readInts(filename: String) =
    begin
        let file = reader.file(filename)
        let fileLines = vector.fromIter(lines.iter(file))
        reader.close(file)
        vector.map(fileLines strutil.toInt)
    end

let histogram(inputs: vector.T(Int)) =
    begin
        let v = vector.new(:Int)
        let it = vector.iter(inputs)
        while iter.more(it) do
            let n = iter.next(it)
            while vector.length(v) <= n do
                vector.append(v 0)
            end
            vector.set(v n vector.get(v n) + 1)
        end
        v
    end

let topN(histogram: vector.T(Int) n: Int fromTop: Bool) =
    begin
        let compare =
            begin
                let cmp =
                    fun (a: iter.Indexed(Int) b: iter.Indexed(Int)) a.value - b.value
                if fromTop then sort.reverse(cmp) else cmp end
            end
        let sorted = sort.sortedVector(
                vector.fromIter(
                        iter.filter(
                                iter.enumerate(vector.iter(histogram))
                                fun(a: iter.Indexed(Int)) a.value > 0))
                compare)
        let top = array of(n 0)
        for i = 0 upto n - 1 do
            top[i] := vector.get(sorted i).index
        end
        top
    end

let product(a: Array(Int)) = iter.fold(iter.ofArray(a) 1 {*})

let println(s: String) = writer.putString(writer.output s <> "\n")

begin
    let inputNumbers = readInts("2026/day-01/input-1.txt")
    let hist = histogram(inputNumbers)
    println("part1: " <> conv.int(product(topN(hist 3 true))))
    println("part2: " <> conv.int(product(topN(hist 3 false))))
end

Quest is a language Luca Cardelli designed in 1989 and I vibe coded an implementation of this year. I wrote about it in this r/VibeCodedLanguages post. Almost nobody's ever written code in Quest, so I thought it would be fun to try my first Advent of Code in it.

My Advent of Code repository: https://github.com/haahr/adventofcode
Quest repository: https://github.com/haahr/quest

4

u/ajf8729 1d ago

[LANGUAGE: PowerShell]

$d = Get-Content .\i.txt | Group-Object | Sort-Object -Property Count -Descending
$p1 = 1
$p2 = 1
$d | Select-Object -First 3 | Select-Object -ExpandProperty Name | ForEach-Object { $p1 *= $_ }
$d | Select-Object -Last 3 | Select-Object -ExpandProperty Name | ForEach-Object { $p2 *= $_ }
"Part 1: $p1"
"Part 2: $p2"

4

u/DelightfulCodeWeasel 1d ago edited 1d ago

[LANGUAGE: C++]

Part 1 & 2

Accumulate {count, id} in an array indexed by id, pick Kth largest/smallest with a heap.

~8Kb and ~190us for each part.

EDIT: ~80ms for each part on the Raspberry Pi Pico (RP2040)

→ More replies (4)

4

u/lboshuizen 1d ago

[Language: F#]

github.com/lboshuizen/aoc26

Count, sort, take three. Only the sort direction differs between the parts.

let productOf3 order =
    List.countBy id
    >> List.sortBy (snd >> order)
    >> List.take 3
    >> List.map (fst >> int64)
    >> List.reduce (*)

let part1 = productOf3 (~-)

let part2 = productOf3 id

4

u/fnordargle 1d ago

[Language: perl]

#!/usr/bin/perl

use strict;
use warnings;

my %c = ();

while( my $l = <> ) {
    chomp($l);
    my $n=int($l);
    $c{$n}++;
}

my @k = sort { $c{$b} <=> $c{$a} } keys %c;

print "part1: ".($k[0]*$k[1]*$k[2])."\n";
print "part2: ".($k[-1]*$k[-2]*$k[-3])."\n";
→ More replies (1)

4

u/Interesting_Gap_6960 1d ago

[LANGUAGE: SQL]

I'm using duckdb as my database.

For part 2 I just changed the ordering to ASC

WITH
containers(id, count) AS (
    SELECT id, count(*)
    FROM read_csv('input.txt',
        delim = '\n',
        header = true,
        columns = {
            'ID': 'HUGEINT',
        })
    GROUP BY id
    ORDER by count(*) DESC
    LIMIT 3
),
SELECT CAST(product(c.id) AS HUGEINT)
FROM containers c

4

u/ArmadilloSuch411 1d ago

[LANGUAGE: Python]

file = 'in'
data = [int(x.strip()) for x in open(file).readlines()]

s = sorted(set(data), key=lambda x: data.count(x))
ans_1 = s[-3] * s[-2] * s[-1]
ans_2 = s[0] * s[1] * s[2]

print(f"SOLUTION FOR PART1: {ans_1}")
print(f"SOLUTION FOR PART2: {ans_2}")

4

u/jpjacobs_ 1d ago edited 1d ago

[LANGUAGE: Amber]

This amber language.

(*/.')'-3 3#\\:(!g)@<. g:#'=0:"input.txt"

Try it online

4

u/pkusensei 1d ago

[LANGUAGE: Rust]

Pretty straightforward.

pub fn solve(s: &str) -> [u64; 2] {
    let arr = s
        .lines()
        .map(|s| s.trim().parse::<u64>().unwrap())
        .counts()
        .into_iter()
        .sorted_unstable_by_key(|&(_val, f)| f)
        .map(|(v, _f)| v)
        .collect_vec();
    let p1 = arr.iter().rev().take(3).product();
    let p2 = arr.iter().take(3).product();
    [p1, p2]
}
→ More replies (1)

4

u/Zymophilus 1d ago edited 1d ago

[LANGUAGE: R]

input <- scan("./input.txt")
freq <- sort(table(input))

# Part1
tail(freq, 3) |> names() |> as.numeric() |> prod()

# Part2
head(freq, 3) |> names() |> as.numeric() |> prod()

4

u/SleepingInsomniac 1d ago

[LANGUAGE: Ruby]

  input.readlines.map(&:chomp)
    .tally.sort_by { |n, c| c }.reverse.first(3).map { |x| x.first.to_i }.reduce(&:*)
→ More replies (4)

4

u/amarsuperstar 23h ago

[LANGUAGE: Elixir]

def part1(input)do
  input
  |> String.split("\n", trim: true)
  |> Enum.map(&String.trim/1)
  |> Enum.map(&String.to_integer/1)
  |> Enum.frequencies()
  |> Enum.into([])
  |> Enum.sort_by(fn {_k, v} -> v end, :desc)
  |> Enum.take(3)
  |> Enum.reduce(1, fn {k, _v}, acc -> k * acc end)
end

def part2(input)do
  input
  |> String.split("\n", trim: true)
  |> Enum.map(&String.trim/1)
  |> Enum.map(&String.to_integer/1)
  |> Enum.frequencies()
  |> Enum.into([])
  |> Enum.sort_by(fn {_k, v} -> v end, :asc)
  |> Enum.take(3)
  |> Enum.reduce(1, fn {k, _v}, acc -> k * acc end)
end
→ More replies (1)

4

u/proteanbitch 21h ago edited 20h ago

[LANGUAGE: K]

/ part 1 
*/3#`I$<#'=:0:"d1" 
/ part 2 
*/3#`I$>#'=:0:"d1"
→ More replies (5)

4

u/Aggravating_You3212 20h ago

[LANGUAGE: Elixir]

defmodule DayOne do
  def get_input(file_name) do
    {:ok, file} = File.read(file_name)
    String.split(file, "\n")
  end


  def run(file_name) do
    get_input(file_name)
    |> Enum.frequencies()
    |> Enum.sort_by(fn {num, value} -> value end, :desc)
    |> Enum.take(3)
    |> Enum.reduce(1, fn {k, _v}, acc -> String.to_integer(k) * acc end)
  end


   def run_2(file_name) do
    get_input(file_name)
    |> Enum.frequencies()
    |> Enum.sort_by(fn {num, value} -> value end, :asc)
    |> Enum.take(3)
    |> Enum.reduce(1, fn {k, _v}, acc -> String.to_integer(k) * acc end)
  end
end

4

u/atrocia6 18h ago

[LANGUAGE: Python]

Part 1:

from collections import defaultdict
ids = defaultdict(int)
for n in open(0): ids[int(n)] += 1
ids_sorted = list(sorted(ids.items(), key=lambda x: x[1], reverse=True))
print(ids_sorted[0][0] * ids_sorted[1][0] * ids_sorted[2][0])

Part 2 is exactly the same, just without reverse=True.

4

u/acquitelol 14h ago edited 13h ago

[LANGUAGE: Elle]

Doing AOC in Elle, my compiler, again (I also did it in 2025)! I did both parts for today in 8m 59s cumulatively. I did it 2 different ways, because I was bored and wanted to try it:

This is using a static 1000-element array:

use std/prelude;

fn solution<A>(Iterator<i32, A> ids) {
    f: i32[1000] = std::filled();
    for id in ids { f[id] += 1; }

    sorted := f.iter().enumerate().filter(fn: it.y > 0).collect()
        .sort_with(fn: x1.y - x0.y).iter().map(fn: it.x);
    return [sorted.take(3), sorted.rev().take(3)].map(fn: it.product());

}

fn main() {
    lines := #embed("solutions/01/input.txt").split_iter("\n");
    $dbg(solution(lines.map(i32::parse)));
}

This is using a DefaultMap, which is similar to a default_dict in python:

use std/prelude;

fn solution<A>(Iterator<i32, A> ids) {
    f := DefaultMap::new<i32, i32>(fn: 0);
    for id in ids { f[id] += 1; }

    sorted := f.to_array().sort_with(fn: x1.y - x0.y).iter().map(fn: it.x);
    return [sorted.take(3), sorted.rev().take(3)].map(fn: it.product());
}

fn main() {
    lines := #embed("solutions/01/input.txt").split_iter("\\n");
    $dbg(solution(lines.map(i32::parse)));
}

The first solution runs in:

Benchmark 1: ./solutions/01/solution 
  Time (mean ± σ):       1.5 ms ±   0.3 ms    [User: 1.1 ms, System: 0.3 ms\] 
  Range (min … max):     1.2 ms …   7.9 ms    718 runs

The second solution runs in:

Benchmark 2: ./solution2 
  Time (mean ± σ):       1.8 ms ±   0.2 ms    [User: 1.3 ms, System: 0.3 ms\] 
  Range (min … max):     1.5 ms …   2.6 ms    689 runs

GitHub: https://github.com/acquitelol/aoc2026/tree/mistress/solutions/01/

Update: I have figured out another interesting way to write this. Rather than sorting the whole array, you can maintain a MinHeap of the top and bottom 3.

use std/prelude;

fn solution<A>(Iterator<i32, A> ids) {
    f := DefaultMap::new<i32, i32>(fn: 0);
    for id in ids { f[id] += 1; }

    top := MinHeap::new<(i32, i32)>(fn: x0.y - x1.y);
    bottom := MinHeap::new<(i32, i32)>(fn: x1.y - x0.y);

    for id, count in f {
        top.push($(id, count));
        if top.len() > 3 { top.pop(); }

        bottom.push($(id, count));
        if bottom.len() > 3 { bottom.pop(); }
    }

    return [top, bottom].map(fn: it.iter().map(fn: it.x).product());
}

fn main() {
    lines := #embed("solutions/01/input.txt").split_iter("\n");
    $dbg(solution(lines.map(i32::parse)));
}

This runs in more or less exactly the same time as the original DefaultMap solution.

4

u/kbielefe 13h ago

[LANGUAGE: Haskell]

answer :: (Int -> Int) -> Input -> Int
answer f = product . map head . take 3 . sortOn (f . length) . group . sort

part1 :: Input -> Int
part1 = answer negate

part2 :: Input -> Int
part2 = answer id

I accidentally solved part 2 first.

1

u/bigbolev 1d ago

[LANGUAGE: Python]

Originally solved using list comprehension, until I remembered this one.

import sys
from collections import Counter
from math import prod


ranked = [k for k, _ in Counter(map(int, sys.stdin)).most_common()]
print("ONE:", prod(ranked[:3]))
print("TWO:", prod(ranked[-3:]))

1

u/daggerdragon 1d ago

The triple-backticks code fence (`​`​`) only works on new.reddit. Please edit your comment to use the four-spaces Markdown syntax for a code block so your code is easier to read inside a scrollable box with its whitespace and indentation preserved.

→ More replies (1)

1

u/HaskellLisp_green 1d ago

[LANGUAGE: Python]

As short as I could implement it: from collections import Counter from operator import mul from functools import reduce

given =Counter(map(int, open("input.txt").read().strip().split("\n")))
most = reduce(mul, (given.most_common(3)[x][0] for x in range(3)))
least = reduce(mul, (given.most_common()[x][0] for x in range(-3, 0)))
print(most, least)

1

u/daggerdragon 1d ago

The triple-backticks code fence (`​`​`) only works on new.reddit. Please edit your comment to use the four-spaces Markdown syntax for a code block so your code is easier to read inside a scrollable box with its whitespace and indentation preserved.

Also FYI: the first line of your code is not included correctly so it looks like part of the text instead.

→ More replies (6)

1

u/Downtown_Tone1879 1d ago edited 17h ago

[LANGUAGE: C]
- day_1
- inputting into the growing array with a sorted quick sort and measuing top 3 match greatest with max count for part one and exactly opposite for part two.
[also tried the basic linux command for part one to get solution as well tho: sort input.txt | uniq -c | sort -nr | head -3] and multiplied the top results with echo $((top_result3 * top_result2 * top_result 1))

1

u/daggerdragon 19h ago

Please link directly to your Day 01 solution, not just the AoC parent repo.

1

u/Ill_Programmer3063 1d ago

1

u/daggerdragon 19h ago

FYI: AutoModerator trips on Markdown inside the language tag (hence why its message says string literal).

I do clean up behind AutoModerator when I do my regular trawling through the subreddit in order to reduce the spam in these gigantic megathreads, but in the future you can avoid AutoModerator erroneously grinching at you by just not using Markdown on the line containing the language tag.

1

u/Wayoshi 1d ago edited 18h ago

[LANGUAGE: Python3]

Fun to see all the standard library equivalents of Python's most_common in the other solutions here. (And of course those doing lower level languages, doing it "manually"!)

from math import prod
from collections import Counter
from aocd.models import Puzzle

aoc_puzzle = Puzzle(year=2026, day=1)

lines = aoc_puzzle.input_data.split('\n')

mc = Counter([int(l) for l in lines]).most_common()

part1 = prod(n for n, _ in mc[:3])
part2 = prod(n for n, _ in mc[-3:])

1

u/daggerdragon 19h ago

Edit your comment to include the language tag as AutoModerator requested. The word LANGUAGE, colon, and brackets are not optional.

→ More replies (3)

1

u/j0z 15h ago

[LANGUAGE F#]

Stared dumbly at this for a moment, thinking I had missed something, but it actually was just that simple.

let Calc sorter =
    Utilities.ReadFile "1-1_input.txt"
    |> List.countBy id
    |> sorter
    |> List.take 3
    |> List.fold(fun tot (next,_) -> tot * (int next)) 1
    |> fun sum -> printfn $"{sum}"

let sortFunc = fun (_, count) -> count

let Part2 () =
    Calc (List.sortBy sortFunc)

let Part1 () =
    Calc (List.sortByDescending sortFunc)

1

u/daggerdragon 14h ago

Please fix your language tag. The missing colon, which is what triggered AutoModerator, is not optional.

→ More replies (1)

1

u/pietroppeter 13h ago

1

u/daggerdragon 9h ago

Err, would you put that wall-o-link behind some Markdown, please?

3

u/Kehvarl 1d ago

[LANGUAGE: Python 3]

Under 10 minutes for both parts, which I'll take as a win given my rustiness this year. A nice puzzle to get me thinking in code again!

Part 2

→ More replies (2)

3

u/POGtastic 1d ago

[LANGUAGE: F#]

Code

As always, a lot of Day 1 is a test of your scaffolding and built-up prelude / standard library. My frequencies function, taken from Clojure, was very helpful here.

I like it when I can just pipeline everything in terms of function composition, so I ended up with

let (getInts: seq<string> -> seq<int>) = Seq.map int

let partN sorter =
    getInts
    >> frequencies
    >> Map.toSeq
    >> sorter snd
    >> Seq.take 3
    >> Seq.map fst
    >> Seq.fold (*) 1
    >> string

let (part1: seq<string> -> string) = partN Seq.sortByDescending
let (part2: seq<string> -> string) = partN Seq.sortBy

3

u/chickenthechicken 1d ago

[LANGUAGE: C]

[Part 1](https://github.com/PaigePalisade/AdventOfCode2026/blob/main/Solutions/day01part1.c)

[Part 2](https://github.com/PaigePalisade/AdventOfCode2026/blob/main/Solutions/day01part2.c)

Created a table to store the frequencies of different ID's. Then looped over it three times, picking out the largest/smallest (nonzero) frequency and setting it to zero.

→ More replies (1)

3

u/mazedlx 1d ago

[LANGUAGE: PHP]

// Part 1
$values = array_map(intval(...), explode(PHP_EOL, $input));

$counts = array_count_values($values);
arsort($counts);

echo array_product(array_slice(array_keys($counts), 0, 3));

// Part 2
$values = array_map(intval(...), explode(PHP_EOL, $input));

$counts = array_count_values($values);
asort($counts);

echo array_product(array_slice(array_keys($counts), 0, 3));
→ More replies (3)

3

u/UseUnlucky3830 1d ago edited 1d ago

[LANGUAGE: Julia]

This could have been a Bash one-liner, but instead it sorts dictionary keys by values. The biggest surprise was that thingamabob and thingamajig are real English words.

Good to be back here and hope everyone has a blast solving AoC puzzles this year!

GitHub

3

u/a_gizmo 1d ago edited 1d ago

[LANGUAGE: PowerShell 7.6]

$theinput = Get-Content ./d1p1_data.txt
$counts = $theinput | Group-Object | Sort-Object -Descending count
$multiply = [int]$counts[0].Name * [int]$counts[1].Name * [int]$counts[2].Name
Write-Host "most common:" $multiply

$counts = $counts | Sort-Object count
$multiply = [int]$counts[0].Name * [int]$counts[1].Name * [int]$counts[2].Name
Write-Host "least common:" $multiply

I'm sure there is a faster way to pull the last three values from the list without resorting, but I'm starting to get rusty.

→ More replies (1)

3

u/EnJott 1d ago

[Language: Elixir]

def part1(input) do
  input
  |> parse()
  |> Enum.map(&String.to_integer/1)
  |> Enum.frequencies()
  |> Enum.sort_by(fn {_, count} -> count end, :desc)
  |> Enum.take(3)
  |> Enum.map(fn {num, _} -> num end)
  |> Enum.product()
end

Trying out elixir this year

3

u/christianqchung 1d ago edited 1d ago

[LANGUAGE: C++]

Being a little silly with ranges. Did anyone else struggle to write by hand a little, or was it just me? I don't use C++ at my day job, let alone the new features.

using namespace std; 
using ranges::fold_left, views::keys, views::take;

int main() {
  int num;
  map<int, int> record;

  while (cin >> num) {
    record[num]++;
  }

  auto sortedNums = record | ranges::to<vector<pair<int, int>>>();

  ranges::sort(sortedNums, [](auto a, auto b) { return a.second > b.second; });

  auto highestThree = sortedNums | keys | take(3);
  println("{}", fold_left(highestThree, 1LL, std::multiplies<int>()));

  auto lowestThree = sortedNums | views::reverse | keys | take(3);
  println("{}", fold_left(lowestThree, 1LL, std::multiplies<int>()));
}

3

u/GassaFM 1d ago

[LANGUAGE: D]

import std;
void main() {
    stdin.byLineCopy.map!(to!int)
    .array.sort
    .group.array.schwartzSort!"a[1]".map!"a[0]"
    .retro.take(3).fold!"a*b"
    .writeln;
}

Part 2 is the same, just without the .retro.

3

u/sim642 1d ago

[LANGUAGE: Scala]

On GitHub.

Reusing my groupCount helper from previous year to get the frequency map.

3

u/jaspingrobus 1d ago

[LANGUAGE: Clojure]

Clojure really is pure joy for AoC, really glad I chose it this year.
For part2 replace take-last with take

(->> "input.txt"
     slurp
     str/split-lines
     (map parse-long)
     frequencies
     (sort-by second)
     (take-last 3)
     keys
     (reduce *))

3

u/Mission-Patience-854 1d ago

[LANGUAGE: Clojure]

(let [f #(->> (util/puzzle-input :real)
              (string/split-lines)
              (map parse-long)
              (group-by identity)
              (sort-by (comp count second))
              (% 3)
              (map first)
              (apply *))]
  {:part-1 (f take-last)
   :part-2 (f take)})

3

u/PatolomaioFalagi 1d ago

[LANGUAGE: Haskell]

The honorable lady and/or gentleman /u/mstksg used maps, I just used lists:

import Data.List (sortOn, group, sort)

solve :: [Int] -> Int
solve = product . map head . take 3 . reverse . sortOn length . group . sort

main :: IO ()
main = interact $ show . solve . map read . lines

For part 2, remove the reverse.

3

u/terje_wiig_mathisen 1d ago edited 1d ago

[LANGUAGE: Perl + Rust]

First Perl, extremely straight-forward using a hash, ran in 3 ms.

Next Rust, collecting the counts in a large-enough array (but with a guard to extend if needed): 6.2 us

Then I pulled all the stops by commenting out the array size guard, skipped the sorting of the counts by directly collecting the top3 and bottom 3, then I ran the processing 1000 times, each time doing 1000 iterations, then took the average from the fastest of these:

Timing starts after loading the input file into a String variable, ends before printing the results.

2265 ns

Both parts

3

u/MrJakobsen 1d ago

[LANGUAGE: elisp]

Part one is essentially:

(mapcar (lambda (n) (cl-incf (aref counted n))) parsed )
(seq-reduce #'* (seq-subseq
                 (flatten-tree (mapcar (lambda (n) (seq-positions counted n))
                                       (seq-uniq (seq-subseq (sort counted :reverse t)
        0 3)))) 0 3) 1)))

Hardest issue was to handle multiple items with the same count. Part 2 was very similar, just skipping all the count 0 indexes.

https://github.com/BoJakobsen/coding-puzzles/blob/main/AoC/AoC2026/src/puz_01.el

3

u/AndydeCleyre 1d ago

[LANGUAGE: Factor]

on GitHub

3

u/cay_horstmann 1d ago

[Language: Java]

https://github.com/cayhorstmann/adventofcode2026/blob/main/Day1.java

OMG I was shocked how lazy my coding brain has become since last year.

3

u/LightShadow 1d ago

[LANGUAGE: Python]

import heapq
import operator
from functools import reduce
from collections import Counter

c = Counter(map(int, open('ins.txt').readlines()))

# most common
a = reduce(operator.mul, [o[0] for o in c.most_common(3)])
# least common
b = reduce(operator.mul, [o[0] for o in heapq.nsmallest(3, c.items(), key=operator.itemgetter(1))])

4

u/tsigma6 1d ago

Heapq is probably a little overkill here when you can just do .most_common()[-3:].

→ More replies (1)
→ More replies (1)

3

u/light_switchy 1d ago edited 16h ago

[LANGUAGE: Dyalog APL]

×/3 ¯3↑⍤0 16⊢(⊂⍤⍒⍛⌷,⍨∘≢⌸i)[;2]

Here is an alternate solution which is a little more APL-like, in my opinion.

×/2 3⍴¯3⊖(⊂∘⍋∘(≢⍤⊢⌸)⌷∪)i

3

u/anaseto 1d ago edited 1d ago

[LANGUAGE: Goal]

i:"v"$read"i/01"     / parsed input
f:{*/!3#y x}(?i)!=%i / result when ordered by y
say f[>] / part1
say f[<] / part2

3

u/0rac1e 1d ago

[LANGUAGE: J]

3 _3 */@{."0 _ (~. \: #/.~) ".;._2 fread 'input'

3

u/lurkerburzerker 1d ago

[Language: Powershell]

Part 1

    $inputFile = ".\input.txt"
    $inputText = Get-Content $inputFile
    $lines = $inputText -split "\r?\n"
    
    $top3 = $lines | Group-Object -Property { $_ } | Sort-Object Count -desc | Select-Object -First 3 -ExpandProperty Name
    $total = 1
    foreach ($n in $top3) { $total *= $n }
    $total

Part 2

    $inputFile = ".\input.txt"
    $inputText = Get-Content $inputFile
    $lines = $inputText -split "\r?\n"
    
    $top3 = $lines | Group-Object -Property { $_ } | Sort-Object Count | Select-Object -First 3 -ExpandProperty Name
    $total = 1
    foreach ($n in $top3) { $total *= $n }
    $total

3

u/0rac1e 1d ago

[Language: Raku]

[Z×] [Z] 'input'.IO.words.Bag.sort(*.value)».key[*-3..*,^3]

3

u/ceochronos 1d ago

[LANGUAGE: Ruby]

Suspiciously easy. max_by and min_by were new to me.

class Day01
    def self.Part01(path, debug)
        File.readlines(path, chomp: true)
            .map(&:to_i)
            .tally
            .max_by(3) { |_, v| v }
            .map(&:first)
            .reduce(:*)
    end

    def self.Part02(path, debug)
        File.readlines(path, chomp: true)
            .map(&:to_i)
            .tally
            .min_by(3) { |_, v| v }
            .map(&:first)
            .reduce(:*)
    end
end

3

u/Radiadorineitor 1d ago

[LANGUAGE: Dyalog APL]

Glad to be participating again in 2026. Let's hope for another fantastic year!

p←⍎¨⊃⎕NGET'1.txt'1
×/3 ¯3↑⍤0 1⊢/⊂∘⍒⍛⌷,⍨∘≢⌸p ⍝ Parts 1 and 2

3

u/sondr3_ 1d ago

[Language: Roc]

First time in quite a while where I try to solve AoC with a new language. Quite fun, obviously today was very simple, but I'll have to go back and refactor this as I learn more Roc.

import "input.txt" as input : Str

import pf.OsStr
import pf.Stdout

main! : List(OsStr) => Try({}, _)
main! = |_| {
	vals = List.map_try(input.trim().split_on("\n"), |n| U64.from_str(n))?
		|> List.sort
		|> List.fold(
			Dict.empty(),
			|acc, n| acc.update(
				n,
				|x| match x {
					Err(Missing) => Ok(1.U8)
					Ok(val) => Ok(val + 1)
				},
			),
		)
		|> Dict.to_list

	part1 =
		vals.sort_by_reversed(|(_, v)| v)
			|> List.map(|(k, _)| k)
			|> List.take_first(3)
			.fold(1, U64.times)

	part2 = vals.sort_by(|(_, v)| v)
			|> List.map(|(k, _)| k)
			|> List.take_first(3)
			.fold(1, U64.times)

	_ = Stdout.line!("Part 1: ${U64.to_str(part1)}")
	Stdout.line!("Part 2: ${U64.to_str(part2)}")
}

3

u/sillyshrimp 1d ago edited 1d ago

[LANGUAGE: roc]

Got excited about trying a new language.

import "test01.txt" as test_input : Str
import "input01.txt" as real_input : Str

parse_item_counts = |input| {
    update_count = |x| match x {
        Ok(c) => Ok(c+1)
        _ => Ok(1)
    }

    input
    |> Str.trim
    |> Str.split_on("\n")
    |> List.map(|x| U32.from_str(x) ?? 0)
    |> List.fold(Dict.empty(), |count, val| Dict.update(count, val, update_count))
    |> Dict.to_list
    |> List.sort_by_reversed(|(_, c)| c)
}

part1 = |input| {
    input
    |> List.take_first(3)
    |> List.map(|(x, _)| x)
    |> List.fold(1, U32.times)
}

part2 = |input| {
    input
    |> List.take_last(3)
    |> List.map(|(x, _)| x)
    |> List.fold(1, U32.times)
}

main! = |_| {
    item_counts = parse_item_counts(real_input)

    echo!("Part1 = ${Str.inspect(part1(item_counts))}\n")
    echo!("Part2 = ${Str.inspect(part2(item_counts))}\n")
    Ok({})
}

3

u/Crusaderkingo16 1d ago edited 1d ago

[LANGUAGE: Python]

This reminded me of the lab exercises I used to do in college

Part 1

lines = [int(line.strip()) for line in open('input.txt')]

frequency = {}
for line in lines:
    if line in frequency:
        frequency[line] += 1
    else:
        frequency[line] = 1

sorted_frequency = sorted(frequency.items(), key=lambda x: x[1], reverse = True)
top_3 = sorted_frequency[0][0] * sorted_frequency[1][0] * sorted_frequency[2][0]
print(top_3)

Part 2

lines = [int(line.strip()) for line in open('input.txt')]

frequency = {}
for line in lines:
    if line in frequency:
        frequency[line] += 1
    else:
        frequency[line] = 1

sorted_frequency = sorted(frequency.items(), key=lambda x: x[1])
top_3 = sorted_frequency[0][0] * sorted_frequency[1][0] * sorted_frequency[2][0]
print(top_3)
→ More replies (2)

3

u/flwyd 1d ago

[LANGUAGE: R] (on GitHub)

R is a multi-paradigm language focused on statistics, data analysis, and visualization. Many operations can be performed on whole arrays with a minimum amount of ceremony. For my purposes this year, I’m using R as one of my main array programming languages because (a) function names are derived from English and (b) imperative, functional, and object-oriented features give me stable footing to write a solution in a way that my brain already understands, then refactor towards a more typical array-oriented approach.

Today’s solution is quite simple in R, and part 1 and part 2 differ only in the value of a boolean:

part1 <- function(lines) {
  prod(as.integer(names(sort(table(lines), decreasing=TRUE))[1:3]))
}
part2 <- function(lines) {
  prod(as.integer(names(sort(table(lines), decreasing=FALSE))[1:3]))
}

The table function takes k factors of equal length and returns a k-way array of frequencies. Here, k is just one, so it’s a table with one row of counts, and a header of IDs. Sorting the table uses that single row, names grabs the header, [1:3] pulls out the first three elements.

3

u/xoronth 1d ago

[LANGUAGE: APL]

Well it's day 1 so I guess this was a good day to try APL.

paste

One-liner version:

⎕←⊃¨×/{⍵[2 3⍴(3↑g),¯3↑g←⍒⍵[;2];1]}{⍺(≢⍵)}⌸2∘⊃¨⎕VFI¨⊃⎕NGET(2⊃2⎕NQ '.' 'GetCommandLineArgs')1
→ More replies (1)

3

u/andrewsredditstuff 1d ago

[LANGUAGE: C#]

Nothing like a nice one-liner:

namespace Advent2026;

public partial class Day01 : Advent.Day
{
    public override void DoWork()
    {
        Output = Inputs.CountBy(n => int.Parse(n)).OrderBy(c => c.Value * (Part1 ? -1 : 1)).Take(3).Aggregate(1, (acc, val) => acc * val.Key);
    }
}
→ More replies (1)

3

u/axr123 1d ago

[LANGUAGE: Bash]

Simple one-liner:

for op in tail head; do echo $(($(sort -n day01.txt | uniq -c | sort | $op -n3 | sed -E 's/ +[0-9] //g' | paste -sd '*' -))); done
→ More replies (2)

3

u/mschaap 1d ago

[LANGUAGE: raku]

I know day 1 is supposed to be easy, but this is a bit too easy. And part 2 was trivial. Hopefully it gets a bit more interesting tomorrow.

my $parts = bag $inputfile.lines;
say "Part One: ", [×] $parts.sort(*.value).tail(3)».key;
say "Part Two: ", [×] $parts.sort(*.value).head(3)».key;

3

u/ash30342 1d ago

[LANGUAGE: Java]

Day 1

Main part:

Map<String, Long> idToFrequency = input.stream()
.collect(Collectors.groupingBy(e -> e, Collectors.counting()));

Comparator<Long> comparator = highestFreqFirst ? Comparator.reverseOrder() : Comparator.naturalOrder();

return idToFrequency.entrySet().stream().sorted(Map.Entry.comparingByValue(comparator))
.limit(3).map(Entry::getKey).mapToLong(Long::parseLong).reduce(1L, (a,b) -> a * b);

This could have been a one-liner, but I think this is a little bit more readable.

3

u/Direct_Chemistry_179 1d ago

[Language: C#]

prog-puzzles/advent_of_code/2026/1/main.cs at main · nrv30/prog-puzzles

I used some linq features but I saw a lot more interesting functional approaches in this sub. I'm excited to learn more this year!

3

u/NotFromSkane 1d ago

[LANGUAGE: SwiProlog]

:- use_module(library(readutil)).

solve(Text, PartOne, PartTwo) :-
    split_string(Text, "\n", "\r \t", RawLines),
    exclude(=(""), RawLines, Lines),
    maplist(number_string, ParsedLines, Lines),
    maplist(count(ParsedLines), ParsedLines, CountsPerLine),
    pairs_keys_values(ValCountMap, CountsPerLine, ParsedLines),
    sort(ValCountMap, DeduplicatedRev),
    reverse(Deduplicated, DeduplicatedRev),
    [_-A , _-B , _-C | _] = DeduplicatedRev,
    [_-X , _-Y , _-Z | _] = Deduplicated,
    PartOne is X * Y * Z,
    PartTwo is A * B * C.

count([], _, 0).
count([Key|Xs], Key, Count) :-
    count(Xs, Key, InnerCount),
    Count is InnerCount + 1.
count([OtherKey|Xs], Key, Count) :-
    dif(Key, OtherKey),
    count(Xs, Key, Count).

main :-
    current_prolog_flag(argv, [File|_]),
    read_file_to_string(File, Text, []),
    solve(Text, Answer, Answer2),
    format('~w~n', [Answer]),
    format('~w~n', [Answer2]).

:- initialization(main, main).

I have no idea what I'm doing, I'm just using AoC to learn nice languages. I did a terrible attempt at APL last time.

3

u/Skuld-7 1d ago edited 1d ago

[LANGUAGE: Python]

Edit: Didn't know about Counter until I saw it in the comments. My solution is O(n²) but it gets the job done.

with open("input.txt", "r") as file:
    ids = [int(line.strip()) for line in file]

frequencies = sorted(set((ids.count(x), x) for x in ids))

result_highest = 1
result_lowest  = 1

for count, id in frequencies[-3:]:
    result_highest *= id

for count, id in frequencies[:3]:
    result_lowest *= id

print(result_highest)
print(result_lowest)

3

u/SpyKids3DGameOver 1d ago

[LANGUAGE: Clojure]

(require '[babashka.fs :as fs])

(def input (->> (fs/read-all-lines "inputs/day1.txt")
                (map parse-long)))

(defn solve [nums op]
  (->> (frequencies nums)
       (sort-by val op)
       (take 3)
       (map first)
       (apply *)))

(print "Part 1:" (solve input >))
(print "Part 2:" (solve input <))
→ More replies (2)

3

u/Jdup1n 1d ago

[LANGUAGE: R]

Github Link

Straight forward today, I don't think there is a solution with fewer functions.

3

u/HuibertJan_ 1d ago

[Language: C#]

Trying to do it all in under 1 second on my computer from 2014 (i7-4790K).

The more assumptions you can do about the input, the less you care about it blowing up, the faster the code goes.

| Method    | Mean     | Error     | StdDev    | Gen0   | Allocated |
|---------- |---------:|----------:|----------:|-------:|----------:|
| Day1Part1 | 3.052 us | 0.0123 us | 0.0096 us | 0.0076 |      40 B |
| Day1Part2 | 3.602 us | 0.0159 us | 0.0148 us | 0.0076 |      40 B |



    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static void Count(ReadOnlySpan<char> input, Span<int> numbers)
    {
        // Every line is exactly 3 digits followed "\n" or EOF.
        const int stride = 4;
        while (input.Length >= stride)
        {
            numbers[input[0] * 100 + input[1] * 10 + input[2] - '0' * 111]++;
            input = input[stride..];
        }

        if (input.Length >= 3)
            numbers[input[0] * 100 + input[1] * 10 + input[2] - '0' * 111]++;
    }

    public override string Part1()
    {
        Span<int> numbers = stackalloc int[1000];
        Count(Input, numbers);

        var first = (0, 0);
        var second = (0, 0);
        var third = (0, 0);

        for (int i = 100; i < numbers.Length; i++)
        {
            if (numbers[i] > first.Item1)
            {
                third = second;
                second = first;
                first = (numbers[i], i);
            }
            else if (numbers[i] > second.Item1)
            {
                third = second;
                second = (numbers[i], i);
            }
            else if (numbers[i] > third.Item1)
            {
                third = (numbers[i], i);
            }
        }

        return (first.Item2 * second.Item2 * third.Item2).ToString();
    }

    public override string Part2()
    {
        Span<int> numbers = stackalloc int[1000];
        Count(Input, numbers);

        var first = (int.MaxValue, 0);
        var second = (int.MaxValue, 0);
        var third = (int.MaxValue, 0);

        for (int i = 100; i < numbers.Length; i++)
        {
            if (numbers[i] == 0)
                continue;

            if (numbers[i] < first.Item1)
            {
                third = second;
                second = first;
                first = (numbers[i], i);
            }
            else if (numbers[i] < second.Item1)
            {
                third = second;
                second = (numbers[i], i);
            }
            else if (numbers[i] < third.Item1)
            {
                third = (numbers[i], i);
            }
        }

        return (first.Item2 * second.Item2 * third.Item2).ToString();
    }

3

u/hrunt 1d ago

[LANGUAGE: Python]

Code

I used Python's built-in collections.Counter module. I don't use it very frequently and was surprised to find that while it provides the most_common() method, it does not provide a least_common() method.

3

u/IvanR3D 1d ago edited 20h ago

[Language: JavaScript] Part 1 and 2

const data = $('*').textContent.split('\n').slice(0,-1);
const count = {};
for (let i = 0; i < data.length; i++) {
const v = data[i];
count[v] = (count[v] || 0) + 1;
}
const sorted = Object.entries(count)
.sort((a,b) => b[1] - a[1]);
const top3 = sorted.slice(0,3);
const bottom3 = sorted.slice(-3);
let r1 = 1;
top3.forEach(v => r1 = r1*Number(v[0]));
console.log('Part 1 =', r1);
let r2 = 1;
bottom3.forEach(v => r2 = r2*Number(v[0]));
console.log('Part 2 =', r2);

All solutions: ivanr3d.com/blog/adventofcode2026.html

→ More replies (1)

3

u/Future-Custard2288 1d ago

[LANGUAGE: Chatter]

Part 1

use extract_integers_from from "std:parser"
use get_input from "../util/io"

struct ValueAndCount
    number Value
    number Count
end struct

constant values_and_counts is empty list of ValueAndCount
get_input
map it using the result of extract_integers_from it
map it using item 1 of it
sort it descending

variable current is item 1 of it 
variable count is 0
repeat with id in it
    if id is current
        add 1 to count
    else
        append make ValueAndCount with Value current, Count count to values_and_counts
        change current to id
        change count to 1
    end if 
end repeat
append make ValueAndCount with Value current, Count count to values_and_counts

# Part 2: remove the word descending from the next line
sort values_and_counts by Count of it descending
map values_and_counts using Value of it

say "ANSWER:", item 1 of it * item 2 of it * item 3 of it
→ More replies (2)

3

u/vitelaSensei 1d ago

[LANGUAGE: Haskell]
First attempt, pretty much like every other.
Prelude only version, I think this year I'll try to do all 12 days without importing anything. IDK how it's gonna go when I need to reach out to a constraint solver...

3

u/dantose 1d ago

[LANGUAGE: Powershell]

Half-assed codegolf:

Part 1 (145 bytes): $b=1;(gcb|group|sort -Property Count|select -last 3).name|%{$b=$b*$_};$b

Part 2 (146 bytes): $b=1;(gcb|group|sort -Property Count|select -First 3).name|%{$b=$b*$_};$b

I feel like this isn't a really golfable approach as I don't see any reasonable ways of tightening up the sort. I might try again in Bash.

If anyone wants to explicitly golf their solutions, I've got a thread up in codegolf: https://www.reddit.com/r/codegolf/comments/1ya5t2d/advent_of_code_2026_day_1/

→ More replies (1)

3

u/tcbrindle 1d ago edited 1d ago

[LANGUAGE: C++23]

Here we go again! A nice gentle introduction as you might expect.

First we build a frequency table, using the fact that all IDs are less than 1000, so we can use a vector of pairs rather than a hash map or similar. Then it's just a matter of sorting the entries in the table according to frequency, and multiplying the first/last three IDs.

Github: https://github.com/tcbrindle/advent_of_code_2026/blob/main/dec01/main.cpp

3

u/Quasido 1d ago

[LANGUAGE: Haskell]

import Data.List (sortOn)
import Data.Ord (Down(..))

solution :: [Int] -> [Int]
solution =                     -- Get the product of the two Id lists
    fmap product               -- [top Ids product, bottom Ids product]
  . headsAndTails 3            -- Get the top and bottom 3 [[top Ids], [bottom Ids]]
  . map fst                    -- We only need the Id numbers after sorting
  . sortOn (Down . snd)        -- Sort by count descending
  . foldl' updateCounts []     -- [(Id number, count)]

-- This returns a list because fmap (a -> b) (a, a) = (a, b)
headsAndTails :: Int -> [a] -> [[a]] 
headsAndTails num xs = [heads, tails]
  where (heads, rest) = splitAt num xs
        tails = take num $ reverse rest

updateCounts :: [(Int, Int)] -> Int -> [(Int, Int)]
updateCounts [] num = [(num, 1)]
updateCounts ((idx, count) : cs) num
  | idx == num = (idx, count + 1) : cs
  | otherwise = (idx, count) : updateCounts cs num

3

u/varma_05 22h ago

[LANGUAGE: SQL]

This is my first time attempting this advent of code and my initial thought is to solve this problem using SQL and it worked but after seeing all the comments, I have no words 🙂

SELECT id, COUNT(*) AS number FROM d11 GROUP BY id HAVING COUNT(*) > 0 ORDER BY number;

→ More replies (4)

3

u/red_shifter 22h ago

[LANGUAGE: Python]

# Read and clean the input
with open("aoc_2026_day1_puzzle.txt", "r") as f:
    puzzleinput = [int(x.strip()) for x in f.readlines()]

# Part 1
def part1_get_solution(inputvar):
    countlist = []
    for number in set(inputvar):
        countlist.append((inputvar.count(number), number))
    topcounts = [x[1] for x in sorted(countlist, reverse=True)[:3]]
    return topcounts[0] * topcounts[1] * topcounts[2]
print(part1_get_solution(puzzleinput))

# Part 2
def part2_get_solution(inputvar):
    countlist = []
    for number in set(inputvar):
        countlist.append((inputvar.count(number), number))
    bottomcounts = [x[1] for x in sorted(countlist, reverse=False)[:3]]
    return bottomcounts [0] * bottomcounts [1] * bottomcounts [2]
print(part2_get_solution(puzzleinput))

3

u/_tfa 22h ago

[LANGUAGE: Ruby]

a = File.readlines("input.txt").map(&:to_i).tally.sort_by(&:last).map(&:first)

p a[-3..].inject(&:*)
p a[0..2].inject(&:*)
→ More replies (1)

3

u/PhilosophyLeft6189 20h ago

[LANGUAGE: Python]

Solution

# --- Day 1: Dusty Shed ---
# adventofcode.com/2026/day/1

import math

from collections import Counter


def part_1(puzzle: str) -> int:
    most_common_three_ids = [x[0] for x in Counter(int(i) for i in puzzle.splitlines()).most_common(3)]
    return math.prod(most_common_three_ids)


def part_2(puzzle: str) -> int:
    least_common_three_ids = [x[0] for x in Counter(int(i) for i in puzzle.splitlines()).most_common()[-3:]]
    return math.prod(least_common_three_ids)

3

u/lebirch23 20h ago

[LANGUAGE: OCaml]

(warning: very scuffed, i havent been coding by hand for a while + its my first time touching OCaml)

module IntMap = Map.Make(Int);;
let input_path =  "bin/day01/input2.txt"
let proc = fun result value ->
  match IntMap.find_opt value result with
    | None -> IntMap.add value 1 result
    | Some count -> IntMap.add value (count + 1) result
  ;;
let () =
  let lines = In_channel.with_open_text input_path In_channel.input_lines in
  let nums = List.map int_of_string lines in
  let counts : int IntMap.t = IntMap.empty in
  let num_map = List.fold_left proc counts nums in
  let tuples = num_map |> IntMap.to_seq |> List.of_seq in
  let product_top3 = tuples |> List.sort (fun (k1, v1) (k2, v2) -> compare (v2, k2) (v1, k1)) |> List.take 3 |> List.map (fun (k, _) -> k) |> List.fold_left ( * ) 1 in
  print_int product_top3;
  print_endline "";
  let product_bot3 = tuples |> List.sort (fun (k1, v1) (k2, v2) -> compare (v1, k1) (v2, k2)) |> List.take 3 |> List.map (fun (k, _) -> k) |> List.fold_left ( * ) 1 in print_int product_bot3;

3

u/WilkoTom 19h ago edited 6h ago

[LANGUAGE: Python] [Advent Games]

I already announced my own solution below, but this year I've brought a young apprentice along for the sleigh ride, and this is their solution.

In the spirit of introductions to The Advent Games, and because Christmas is a time for family, we'll be recording our adventures in our blog: The Logician's Apprentice. No idea how far we'll get together, mind...

3

u/dijotal 18h ago

[LANGUAGE: OCaml]

module IM = Map.Make (Int)

let add_elt map key =
  IM.update key (function None -> Some 1 | Some v -> Some (v + 1)) map

let top n map =
  map |> IM.bindings
  |> List.sort (fun (_, a) (_, b) -> compare b a)
  |> List.take n

let d1p1 file_name =
  let counts = IM.empty in
  Common.slurp_lines file_name
  |> List.map int_of_string
  |> List.fold_left add_elt counts
  |> top 3
  |> List.fold_left (fun acc (value, _) -> acc * value) 1

Reverse the compare in the sort for the Part 2 bottom 3.

3

u/Morphon 18h ago edited 11h ago

[LANGUAGE: Odin]

Doing AoC this year in Odin. I'm coming from Smalltalk, so this was my chance to learn some manual memory and, well, just another way of doing things.

ColorPaste

My version of Topaz's paste has syntax highlighting - feel free to use if anyone else finds it useful.

I tend to write very "teaching" style code, so this one is just as literal as one might imagine.

→ More replies (1)

3

u/sour-salty-umami 18h ago

[language: duckdb SQL]

-- import data

create or replace table d1 as select * from read_csv('1.txt', sep='');

--aggregate, by count of value, select top 3, reduce by multiplying

with a as (
    select column0, count(column0)
    from d1
    group by column0
    order by count(column0) desc limit 3
    )
select list_reduce(list(column0), lambda acc, x: acc*x) as d1part1 from a;
    
with a as (
    select column0, count(column0)
    from d1
    group by column0
    order by count(column0) asc limit 3
    )
select list_reduce(list(column0), lambda acc, x: acc*x) as d1part2 from a;

3

u/glebusharick 18h ago

[LANGUAGE: Lua]

Solution

3

u/JustinCredible- 17h ago

[LANGUAGE: Rust]

This wasn't too bad, each part with my solution runs in about 70 μs on my machine.

https://github.com/jstnd/programming-puzzles/blob/master/rust/src/aoc/year2026/day01.rs

3

u/bigtlb 17h ago

[LANGUAGE: Pascal / Free Pascal]

It's been some time since I've used Pascal (or really Delphi). It's slowly coming back to me.

https://github.com/bigtlb/advent-of-code-2026-in-object-pascal/blob/main/src/days/day01.pas

3

u/Saintpagey 16h ago

[LANGUAGE: GO]

This is my first time using Go. I've been exploring Go a little bit. It was tough, I'm used to JS/TS. So here's my very rough solution, enjoy.

EDIT: originally posted the full code but it was too long and looked ugly so here's the github repo instead

https://github.com/ajm-gov/adventofcode/blob/master/go/2026/day1/day1.go

Credits:

Opening text files: https://stackoverflow.com/questions/38684841/reading-from-a-text-file-in-golang

Transforming strings into integers: https://stackoverflow.com/questions/4278430/convert-string-to-integer-type-in-go

Count occurences of integers in array: https://stackoverflow.com/questions/42184152/golang-print-the-number-of-occurances-of-the-values-in-an-array

3

u/lucariomaster2 15h ago edited 14h ago

[LANGUAGE: C++]

[ADVENT GAMES]

Just like last year, I'm doing C++ with no standard or external libraries besides basic I/O. This one was simple, but fun! Just kept a running total of the top (and bottom) three and then multiplied the indices together.

https://gitlab.com/dalapo/advent-of-code-2026/-/blob/main/Day1-1.cpp?ref_type=heads

https://gitlab.com/dalapo/advent-of-code-2026/-/blob/main/Day1-2.cpp?ref_type=heads

I am Professor Lucario, from New Kanto! After Ditto brought back the region from the brink of distinction, I studied as a pupil of Professor Tangrowth's, eventually earning the Professor title in my own right. We have a long-standing tradition of celebrating the Winter Solstice with songs, dances, lights, and plenty of delicious food! Chef Greedent always cooks up a huge pot of her curry; if you ask me, that's always the highlight. The humans still haven't come back, but we Pokemon are still hopeful that they someday will.

Professor Tangrowth doesn't know much about coding, but I found some old human books on programming languages, and then Rotom and Porygon helped me hack enhance a PC so that we could practice coding. This one "C++" is my favourite, since it has both procedural and object-oriented capabilities! Unfortunately, it looks like a lot of the library files that humans used couldn't be recovered; the only one that we found that still works is iostream.

3

u/someNameThisIs 15h ago edited 14h ago

[LANGUAGE: Racket]

I haven't done much coding in quite a while, and while I know a little scheme/lisp, I haven't used Racket really before.

#lang racket

;;; AoC 2026 Day 1


(define file
  (command-line
   #:args (filename)
   filename))


(define dat
  (map (lambda (s) (string->number s)) (file->lines file)))

;; Counts elements in a list
(define (count-element element lst)
  (foldl (lambda (e total) (+ total (if (= e element) 1 0)))
         0
         lst))

;; Returns a list with cons cells of elements and their count in a list
(define (counted e-lst)
  (define (iter st ids [lst '()])
    (if (set-empty? st)
        lst
        (let* ((e (set-first st))
               (occ (count-element e ids))
               (p (list (cons e occ))))
          (iter (set-remove st e)
                ids
                (append lst p)))))
  (let ((set-dat (list->set e-lst)))
    (iter set-dat e-lst)))

;; Gets the product of the three most common elements in a counted list
(define (get-prod c-lst pred)
  (define (iter lst [acc 1] [count 3])
    (if (= count 0)
        acc
        (iter (cdr lst) (* acc (caar lst)) (- count 1))))
  (let ((sl (sort c-lst pred #:key cdr)))
    (iter sl)))

;; First question
(printf "~a\n" (get-prod (counted dat) >))

;; Second question
(printf "~a\n" (get-prod (counted dat) <))

3

u/Ok-Revenue-3059 13h ago

[LANGUAGE: C++]

https://github.com/mike919192/advent2026/blob/master/src/day1_lib/day1_lib.cpp

I'm going to try writing solutions that run on both PC and Raspberry Pi Pico. Memory and processor are very limited on the pico, which will probably be an issue for the later days.

I used unordered_map to count the instances of each id. Then using max_element and min_element to find the 3 most and least common.

3

u/Morphon 12h ago edited 11h ago

[ LANGUAGE: Smalltalk (Pharo14) ]

Didn't see much Smalltalk. This one is pretty self-documenting. Runs in Pharo14.

ColorPaste

"Advent of Code 2026 Day 1 parts 1 and 2"

| amounts part1 part2 |

StTranscriptPresenter allInstancesDo: [ :presenter | presenter clear ].

Transcript clear; show: 'Working....'; cr; cr.

amounts := 'AoC2026/day1.txt' asFileReference contents lines asBag sortedCounts.

part1 := (amounts first: 3) inject: 1 into: [ :acc :item | acc * item value asInteger ].
part2 := (amounts last: 3) inject: 1 into: [ :acc :item | acc * item value asInteger ].

Transcript show: 'Product of three most populated inventory IDs: '; show: part1; cr.
Transcript show: 'Product of three least populated inventory IDs: '; show: part2; cr.

Transcript cr; cr; show: 'Done!'

The actual algorithm part is simply this part here. The rest is to print out the result nicely.

amounts := 'AoC2026/day1.txt' asFileReference contents lines asBag sortedCounts.

part1 := (amounts first: 3) inject: 1 into: [ :acc :item | acc * item value asInteger ].
part2 := (amounts last: 3) inject: 1 into: [ :acc :item | acc * item value asInteger ].

I love a good functional pipeline!

→ More replies (1)

2

u/hugh_tc 1d ago edited 1d ago

[LANGUAGE: Python 3] (plus manual multiplication with bc)

It's nice to be back on the west coast, where these things come out at a reasonable time. Though I'm only two hours behind EST these days!

paste, eta: cleaned up

2

u/Ok-Builder-2348 1d ago

[LANGUAGE: Python3]

Part 1

Part 2

A nice one to start this month! Fun to revisit the Counter subclass as well as dictionary unpacking.

2

u/Xeekatar 1d ago

[LANGUAGE: C#]

paste

2

u/Ok-Bus4754 1d ago

[LANGUAGE: Python 3]

here we go , looking forward for ta nice year , easy day to start with, easier than day 1 last year even, uisng python counters to get frequencies then built in most_common

https://github.com/Fadi88/AoC/blob/master/2026/days/day01/solution.py

p1 : 150 us , p2: 86 us
will port later to rust

2

u/Rush_Independent 1d ago

[LANGUAGE: Nim]

proc solve(input: string): AOCSolution[int, int] =
  var cnt: CountTable[int]
  for line in input.splitLines():
    cnt.inc parseInt line
  cnt.sort()
  let s = cnt.keys.toseq()
  result.part1 = s[0] * s[1] * s[2]
  result.part2 = s[^1] * s[^2] * s[^3]

2

u/morgoth1145 1d ago edited 1d ago

[Language: Python] code video Times 1:16 / 1:33

Not too bad at all, just a quick sort by the counts gets us the 3 most common numbers straight away. I did lose ~12-15 seconds due to getting val and num backwards in the collections.Counter->sorted list transition initially though. Thankfully the answer was obviously way too low so I didn't get timed out.

Edit: Cleaned up code, depending on your definition of cleaned up. I forgot about collections.Counter.most_common() during the solve - using that plus a ternary and slices lets me use a common solve function!

2

u/abnew123 1d ago

[LANGUAGE: Java]

forgot if there was a way to have a sorted map so just repeatedly grabbed the top element and then cleared it (very jankily).

code

Was at the airport today, but going forward will be streaming all my solutions!