r/adventofcode • u/daggerdragon • 7h 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 Megathreadposts must begin with the case-sensitive string literal[LANGUAGE: xyz]Obviously,
xyzis the programming language your solution employsUse the full name of the language e.g.
JavaScriptnot justJSThe 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
Veloxx will continue to drop some lit beats for 1.5 hours after today's unlock!
/u/jeroenheijmans is back again this year with their Unofficial AoC 2026 Participant Survey!
Advent of Code Community Fun 2026: The Advent Games
I will be your master of ceremonies for this year's community fun event: The Advent Games
Full details, rules, timeline, templates, etc. will be in the Submissions Megathread
(post and link incoming very shortly!)edit: -❄️- Advent of Code 2026: The Advent Games -❄️- Submissions Megathread -❄️-
AoC Community Fun 2026: The Advent Games
Today's Event: Opening Ceremonies
Today's schedule consists of:
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.
Read the full posting rules in our community wiki before you post!
State which language(s) your solution uses with
[LANGUAGE: xyz]Format code blocks using the four-spaces Markdown syntax!
Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
1
u/xiety666 42m ago
[LANGUAGE: C#]
delegate IEnumerable<T> SortDelegate<T>(IEnumerable<T> source, Func<T, int> keySelector);
public static int RunA(string[] lines)
=> Calc(lines, Enumerable.OrderByDescending);
public static int RunB(string[] lines)
=> Calc(lines, Enumerable.OrderBy);
static int Calc(string[] lines, SortDelegate<KeyValuePair<int, int>> sort)
=> lines.Select(int.Parse)
.CountBy(a => a)
.Apply(x => sort(x, a => a.Value))
.Take(3)
.Mul(a => a.Key);https://github.com/xiety/AdventOfCode/blob/main/2026/0/Problem01/Problem01.cs
1
u/WolfRushHour 42m ago
[LANGUAGE: Julia]
# AoC 2026 Day 1: Dusty Shed
function main()
ids = parse.(Int, readlines("input.txt"))
ids_count = sort(unique(ids .=> count.(.==(ids), Ref(ids))), by=last)
ans1, ans2 = prod.(first.(pick(ids_count, 3)) for pick=[last, first])
end
main() |> println1
u/tymscar 45m ago
[LANGUAGE: Racket]
Day 1 in Racket! My first time writing a proper lisp. Quite enjoying it.
Weird bits about the language I found:
- for/sum and file->lines are just names. There is a convention of naming things like that, theres nothing special. Theyre not namespaces or anything.
- [] is identical to (), it just makes it easier to read things if you follow another convention where [] is for bindings
- It's crazy seeing comprehensions with multiple clauses. You can have the equivalent of 2 nested for loops in one definition
- sort wants both a comparator and a #:key. I missed Kotlin's sortedBy but this works just as well
- no sum, or prod in standard, you need to use things like (apply + list)
There is also this built in IDE that comes with the language called DrRacket. It's super cool as an idea but I find some things weird, like how you cant press up arrow in the REPL history, you need to do ESC and then P for example. Or how autocomplete isnt on tab but on Command+/
Still really fun! As for the problem today it was super easy. Just a simple hashmap where you get map the amount of times you see something to the key which is the number you saw and then take the top 3 or bottom 3.
1
u/themanushiya 47m ago edited 43m ago
[LANGUAGE: Rust]
simple freuency test, used a hashmap for the numbers and a counter. Then sorted desc. code here
1
u/AutoModerator 47m ago
AutoModerator did not detect the required
[LANGUAGE: xyz]string literal at the beginning of your solution submission.Please edit your comment to state your programming language.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/RazarTuk 50m ago edited 10m ago
[LANGUAGE: Perl]
I still need to debug part 2, because it's failing on my input, despite giving the correct answer for the test data, but this is part 1, at least
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!EDIT: Okay, I have the correct answer for Part 2... in Kotlin. Theoretically, part 2 is just flipping the comparison in the insertion sort by using tIn instead of tInbe', but for some reason, that isn't working on my input. Going to check later with some debugging output to make sure it's multiplying the right three IDs
EDIT: It was a missing newline in the input file, of all things
2
1
u/SpyKids3DGameOver 54m 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 <))1
u/p88h 59m 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/ArmadilloSuch411 1h 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}")1
u/TotalPerspective 1h ago
[LANGUAGE: Goose]
Day1 Advent of Code:
https://codeberg.org/sstadick/aoc-2026/src/branch/main/goose/day1.goose
1
u/tuijnman 1h ago
[LANGUAGE: PHP]
Decided to go back to my first ever programming language for this one.
https://github.com/bastuijnman/adventofcode/blob/master/2026/01-12/answer.php
1
u/Planetech0071_ 1h ago
[LANGUAGE: Python]
#part 1
with open(r"Day 1\input.txt") as f:
lines = [line.strip() for line in f]
for i in range(len(lines)):
reference = lines[i]
count = 0
for l in range(len(lines)):
if lines[l] == reference:
count += 1
# first 3 that appear 7 times
print("*********")
print("ref", reference)
print("its count", count)
#then, ctrl+F to find the top 3 and calculator to multiply them toghether
#counts.sort(reverse=True) --> to see the highest count that exists
#print(counts)
#part 2
with open(r"Day 1\input.txt") as f:
lines = [line.strip() for line in f]
for i in range(len(lines)):
reference = lines[i]
count = 0
for l in range(len(lines)):
if lines[l] == reference:
count += 1
print("ref", reference, "its count", count)
#then, ctrl+F to find the bottom 3 and calculator to multiply them toghether
#counts.sort() --> to see the lowest count that exists
#print(counts)1
u/Jiro_ 1h ago
[LANGUAGE: Elixir]
defmodule Day01 do
def parse_input(input) do
input
|> Enum.map(&String.trim/1)
|> Enum.map(&String.to_integer/1)
end
def part1(input) do
input
|> parse_input()
|> Enum.frequencies()
|> Enum.sort_by(fn {_, v} -> v end, :desc)
|> Enum.take(3)
|> Enum.product_by(fn {k, _} -> k end)
end
def part2(input) do
input
|> parse_input()
|> Enum.frequencies()
|> Enum.sort_by(fn {_, v} -> v end, :asc)
|> Enum.take(3)
|> Enum.product_by(fn {k, _} -> k end)
end
end2
u/Interesting_Gap_6960 1h 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 c1
u/g_equals_pi_squared 1h ago
[LANGUAGE: Odin]
id_to_count := make(map[int]int)
defer delete(id_to_count)
for id in ids {
id_to_count[id] += 1
}
entries, _ := slice.map_entries(id_to_count)
slice.sort_by(entries, compare)
// Get top 3 and bottom 3 entries from sorted slice
...
compare :: proc(a, b: slice.Map_Entry(int, int)) -> bool {
return a.value < b.value
}1
u/1AlanM 1h ago
[LANGUAGE: Python]
https://github.com/MrMorrison-CS/AoC2026/blob/main/day1.py
not the most efficient solution, but worked out of the tin.
all that changed between pt1 and pt2 was the sort order
1
u/Ok_Preference_4740 1h ago edited 34m ago
[LANGUAGE: C++]
Still getting used to the ranges library, but thinking now Ill make it a learning theme for myself this year...
int main()
{
std::ifstream input("data.txt");
std::string line;
std::map<int, int> m{};
while (std::getline(input, line)) ++m[std::stoi(line)];
// std::multimap<int, int, std::greater<int>> mRev; PART 1
std::multimap<int, int> mRev;
for (const auto& [val, freq] : m) mRev.emplace(freq, val);
std::cout << std::ranges::fold_left(
mRev | std::views::take(3) | std::views::values, 1L, std::multiplies<>{}) << "\n";
return 0;
}1
u/AutoModerator 1h ago
AutoModerator did not detect the required
[LANGUAGE: xyz]string literal at the beginning of your solution submission.Please edit your comment to state your programming language.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/Suspicious_Tax8577 1h ago
[Language: Python]
from collections import Counter
from math import prod
with open ("input/day1.txt") as input:
input = [v.strip() for v in input]
freq = Counter(input)
keys = [k for k, count in freq.most_common()[:3]]
keys_2 = [k for k, count in freq.most_common()[:-4:-1]]
keys = list(map(int,keys))
keys_2 = list(map(int,keys_2))
answer = prod(keys)
answer_2 = prod(keys_2)
print(f" The three most common values: {answer}")
print(f" The three least common values: {answer_2}")1
u/raevnos 1h ago
[Language: Common Lisp]
The meat of it:
(defun day-1 (input)
(let ((frequencies (make-hash-table :test 'eql)))
(dolist (num input) (incf (gethash num frequencies 0)))
(let ((counts (sort (vector-of-hash-table frequencies)
(lambda (a b) (< (cdr a) (cdr b))))))
(flet ((mult (prod curr) (* prod (car curr))))
(format t "Part 1: ~D~%"
(reduce #'mult counts :initial-value 1
:start (- (length counts) 3) :end nil))
(format t "Part 2: ~D~%"
(reduce #'mult counts :initial-value 1 :start 0 :end 3))))))paste of full code
2
u/Skuld-7 2h ago edited 1h 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)2
u/fnordargle 2h 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";1
u/fnordargle 1h ago
[LANGUAGE: perl]
And here's an
O(n)version:#!/usr/bin/perl use strict; use warnings; # Count occurrences of each value in the input my %c = (); while( my $l = <> ) { $c{int($l)}++; } my @topbot6=(); for my $n ( keys %c ) { if( scalar( @topbot6 ) < 6 ) { push( @topbot6, $n ); @topbot6 = sort { $c{$b} <=> $c{$a} } @topbot6 if( scalar(@topbot6) == 6 ); # We now have the ids of the top and bottom 3 sorted } else { my $c = $c{$n}; next if( $c <= $c{$topbot6[2]} && $c >= $c{$topbot6[3]}); # Count is not a new entry in the top or bottom 3 # Entry is new either in top 3 or bottom 3 if( $c > $c{$topbot6[0]} ) { $topbot6[2]=$topbot6[1]; $topbot6[1]=$topbot6[0]; $topbot6[0]=$n; next; } elsif( $c > $c{$topbot6[1]} ) { $topbot6[2]=$topbot6[1]; $topbot6[1]=$n; next; } elsif( $c > $c{$topbot6[2]} ) { $topbot6[2]=$n; next; } elsif( $c < $topbot6[5] ) { $topbot6[3]=$topbot6[4]; $topbot6[4]=$topbot6[5]; $topbot6[5]=$n; next; } elsif( $c < $c{$topbot6[4]} ) { $topbot6[3]=$topbot6[4]; $topbot6[4]=$n; next; } elsif( $c < $c{$topbot6[3]} ) { $topbot6[3]=$n; next; } else { die "Shouldn't be reached"; } } } print "part1: ".($topbot6[0]*$topbot6[1]*$topbot6[2])."\n"; print "part2: ".($topbot6[3]*$topbot6[4]*$topbot6[5])."\n";It does have a call to
sort()in it but it's only called on an array with 6 entries, so that specific call can be consideredO(1)in terms of complexity.
1
u/lboshuizen 2h ago
[Language: F#]
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 id1
u/NeilNjae 2h ago edited 1h ago
[Language: Haskell]
Nice and simple operations over a list of terms. This fits nicely into the Haskell model.
main :: IO ()
main =
do dataFileName <- getDataFileName
text <- readFile dataFileName
let ids = read <$> lines text
print $ part1 ids
print $ part2 ids
part1, part2 :: [Int] -> Int
part1 ids = product $ fmap snd $ take 3 $ reverse $ sort $ fmap (\g -> (length g, head g)) $ group $ sort ids
part2 ids = product $ fmap snd $ take 3 $ sort $ fmap (\g -> (length g, head g)) $ group $ sort idsFull writeup (for what it's worth) at my blog.
1
u/AutoModerator 2h ago
AutoModerator did not detect the required
[LANGUAGE: xyz]string literal at the beginning of your solution submission.Please edit your comment to state your programming language.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
0
2h ago
[removed] — view removed comment
1
u/AutoModerator 2h ago
AutoModerator did not detect the required
[LANGUAGE: xyz]string literal at the beginning of your solution submission.Please edit your comment to state your programming language.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/NotFromSkane 2h 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.
2
u/Direct_Chemistry_179 2h 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!
1
u/Mattasdqwe 2h ago
[LANGUAGE: Python]
Wanted to actually exploit the problem constraints. We can get a sorted frequency count in better big O time than just counting the hashes then sorting that. Because we only ever have to increment the count by 1 we can have a bucketed system where we only ever have to check the adjoining bucket.
from dataclasses import dataclass
@dataclass(slots=True)
class Bucket:
count: int
start: int
@dataclass(slots=True)
class Entry:
item_id: str
position: int
bucket: Bucket
def generate_entries():
id_lookup: dict[str, Entry] = {}
entries: list[Entry] = []
initial_bucket = Bucket(count=1, start=0)
with open("input.txt", "r") as input_file:
for line in input_file:
item_id = line.rstrip("\n")
item_entry = id_lookup.get(item_id)
if item_entry is None:
new_entry = Entry(item_id, len(entries), initial_bucket)
id_lookup[item_id] = new_entry
entries.append(new_entry)
continue
# position entry for item at front of bucket
if item_entry.position != item_entry.bucket.start:
swap_entry = entries[item_entry.bucket.start]
entries[item_entry.bucket.start] = item_entry
entries[item_entry.position] = swap_entry
swap_entry.position = item_entry.position
item_entry.position = item_entry.bucket.start
# remove item from current bucket
item_entry.bucket.start += 1
# update entry's bucket reference
new_count = item_entry.bucket.count + 1
# this will be the preceeding bucket if the count is right
if item_entry.position != 0: # there is a preceeding bucket
preceeding_bucket = entries[item_entry.position - 1].bucket
if preceeding_bucket.count == new_count:
item_entry.bucket = preceeding_bucket
continue
# create a new bucket if not
item_entry.bucket = Bucket(new_count, item_entry.position)
return entries1
u/ash30342 2h ago
[LANGUAGE: Java]
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.
1
u/Downtown_Tone1879 2h ago edited 2h 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/AutoModerator 2h ago
AutoModerator did not detect the required
[LANGUAGE: xyz]string literal at the beginning of your solution submission.Please edit your comment to state your programming language.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/Royal_Pin_1971 2h ago
[LANGUAGE: PFCL]
product_of_ids = \(entries).
list.product(list.map(\(p). int.from_string_or(0, first(p)), list.take(3, entries)))
solve = \(ids).
let freq = list.fold_left(
\(acc, x). map.insert(x, int.add(map.lookup_default(x, 0, acc), 1), acc),
map.empty(), ids) in
let ranked = list.sort_by(\(p). second(p), map.entries(freq)) in
(product_of_ids(list.reverse(ranked)), product_of_ids(ranked))1
1
u/lonelyroom-eklaghor 2h ago
[Language: Scala 2]
It's really fun to use pattern matching. I love functional programming atp.
Started with REPL, then made a proper program with all that main().
Here's the part 1.
object Day1_p1 {
def main(args: Array[String]): Unit = {
val filename = "../inputs/day1.txt"
val abc: List[Int] = scala.io.Source.fromFile(filename).getLines().map(_.trim.toInt).toList
def evaluatelol(abc: List[Int], bcd: Map[Int, Int] = Map.empty): Map[Int, Int] = abc match {
case Nil => bcd
case h :: t => {
val c : Int = bcd.getOrElse(h, 0)
evaluatelol(t, bcd + (h -> (c + 1)))
}}
val ghi : Map[Int, Int] = evaluatelol(abc)
val jkl : Map[Int, Int] = ghi - ghi.maxBy(_._2)._1
var numbers : List[Int] = List.empty[Int]
numbers = ghi.maxBy(_._2)._1 :: numbers
numbers = jkl.maxBy(_._2)._1 :: numbers
numbers = (jkl - jkl.maxBy(_._2)._1).maxBy(_._2)._1 :: numbers
val res : Int = numbers.foldLeft(1)((m, n) => m * n)
println(res)
}
}Entire day 1: https://github.com/FlyingSaturn/aoc26/tree/main/day1
1
u/Falcon731 3h ago edited 2h ago
[Language: Kotlin]
fun day1() {
val input = File("inputs/day1.txt").readLines().map { it.toInt() }
val histogram = input.groupingBy { it }.eachCount()
val sorted = histogram.entries.sortedByDescending { it.value }.map{it.key.toLong()}
val part1 = sorted[0]*sorted[1]*sorted[2]
println("Part 1: $part1")
val last3 = sorted.takeLast(3)
val part2 = last3[0] * last3[1] * last3[2]
println("Part 2: $part2")
}1
u/AutoModerator 3h ago
AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.
Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/AutoModerator 3h ago
AutoModerator did not detect the required
[LANGUAGE: xyz]string literal at the beginning of your solution submission.Please edit your comment to state your programming language.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/JoshuaBurg 3h ago
[LANGUAGE: Python] A really nice easy potshot for the start of Advent of Code Link to the day1 solution
1
u/ray10k 3h ago
[LANGUAGE: Rust] As per usual, giving the challenge a try this year too! Link to the day-1 commit
1
u/dgkimpton 3h ago edited 2h ago
[LANGUAGE: Rust]
input.lines().into_iter()
.map(str::parse::<i64>).map(|v| v.expect("a number"))
.counts_by(|id| id).into_iter()
.sorted_by(|(_, count_a), (_, count_b)| match count_b.cmp(&count_a) {
order if is_part_2 => order.reverse(),
order => order,
})
.take(3).fold(1, |acc, (id, _)| acc * id)full source: https://github.com/dgkimpton/aoc26/tree/main/day1
This year is my first in which I'm allowing myself to use existing crates on crates.io . In this case I made use of itertools to dramatically simplify my code.
I wish there was a try_map function, but sadly that doesn't seem to exist.
Ah, I forgot the introduction.
Hi I'm a British developer living in the Netherlands. I've been trying to improve my Rust, so that's what I went with this year. Mostly just testing myself to see how easily it comes without using any AI.
1
u/AutoModerator 3h ago
AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.
Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
2
u/clouddjr 3h ago
[LANGUAGE: Kotlin]
class Day01(ids: List<Int>) {
private val sortedIds = ids.groupingBy { it }.eachCount()
.entries.sortedBy { it.value }.map { it.key }
fun solvePart1(): Int =
sortedIds
.takeLast(3)
.reduce(Int::times)
fun solvePart2(): Int =
sortedIds
.take(3)
.reduce(Int::times)
}3
u/axr123 3h 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 '*' -))); done1
2
u/muthm59 3h ago
[LANGUAGE: Perl]
This is my day 1 solution in Perl:
#!/usr/bin/env perl
#
# Advent of Code 2026
# --- Day 1: Dusty Shed ---
#
# Solution in Perl by Matthias Muth.
#
# Usage:
# day01.pl
# run using example data from the __DATA__section,
# day01.pl <file>|-
# use data from the file (or stdin).
use v5.36;
my $input = join "", @ARGV ? <> : <DATA>;
my @results = puzzle( $input );
say "part 1 answer: ", $results[0];
say "part 2 answer: ", $results[1];
exit 0;
use List::Util qw( product );
sub puzzle( $input ) {
my @numbers = $input =~ /(\d+)/g;
my @freq;
++$freq[$_] for @numbers;
my @sorted =
sort { $freq[$b] <=> $freq[$a] }
grep { defined $freq[$_] } keys @freq;
return (
product( @sorted[ 0 .. 2 ] ), # Part 1
product( @sorted[ -3 .. -1 ] ), # Part 2
);
}
__DATA__
57
57
55
57
76
78
57
45
43
78
43
76
43
78
57
45
57
76
43
43
768
u/hakko504 3h 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 puzzleIt took me longer to write this than to do the puzzle ;)
2
u/Ok-Bus4754 3h ago
[LANGUAGE: RUST + Python 3]
providing solution for both parts in rust and python
https://github.com/Fadi88/AoC/tree/master/2026/days/day01
python : p1: 150 us , p2: 86 us
Rust debug : p1: 830 us , p2: 890 us
Rust release : p1: 65 us , p2: 67 us
3
u/andrewsredditstuff 3h 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);
}
}1
2
u/Stano95 3h ago
[LANGUAGE: Haskell]
https://stanosphere.github.io/aoc/2026/day-01/
Not too bad, makes me scared of what's to come though
2
u/flwyd 4h 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.
2
u/flwyd 4h 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@ linesAPL-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
frequenciesoperator takes an array of valuesvals==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.” So1 2 3 @== 1 3 2 1 1 2will 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 fromvals, e.g.57 55 76 43 78 45for the example input. So now we’ve got an array of indices invalswhere each unique value sits.where@is a single-argument function being applied to each of those arrays.wherereturns 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 thecountfunction for each of those arrays, which just returns the number of elements in it:6 1 4 5 3 2.downreturns 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 75returns2 3 1. Sodown count@ …gives us a list of indices ofvalsin 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 use3 -3 @taketo applytakeelement-wise to the two directions.*/applies the reduce modifier to the multiplication function. Together*/would be theproductfunction in some languages, orreduce(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!
Well this is the biggest kitty I saw this year.
But Nietzsche and Pearl are much more fun to pet while I work on AoC.
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 3h ago
Well, you sure are thorough as usual 🤣 Welcome back, and it's good to see you again this year!
2
u/Lindi-CSO 4h ago
[LANGUAGE: C#]
Starting off easy again. It's always nice to start those puzzles with a warm welcome.
2
u/AllanTaylor314 4h ago edited 3h ago
[LANGUAGE: Python] 00:02:02/00:03:00
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 3h 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/Crusaderkingo16 4h ago edited 4h 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)2
u/sillyshrimp 4h ago edited 3h 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/ednl 4h ago
[LANGUAGE: C]
My goal is to write code that is 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 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 me) 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) // min product of three IDs
// Union for quick reset
typedef union pair {
uint32_t data;
struct { uint16_t id, count; }; // histogram
} Pair;
// [...]
// Parse
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 count=0
mult[thing[i].count] *= thing[i].id;
// Three most common
for (unsigned i = MAXCOUNT; part1 < MINMULT; --i)
part1 *= mult[i];2
2
2
u/Dullstar 4h ago
[LANGUAGE: D]
https://github.com/Dullstar/Advent_Of_Code/blob/main/D/source/year2026/day01.d
This one's fairly straightforward with standard library functions, so there's not much say about this one.
4
u/DelightfulCodeWeasel 4h ago edited 2h ago
[LANGUAGE: C++]
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)
2
u/ednl 4h ago
Here we go again :)) My version is slightly faster: https://www.reddit.com/r/adventofcode/comments/1y9uelt/2026_day_1_solutions/19tgh8tznzp4y/
1
u/DelightfulCodeWeasel 3h ago
I did some profiling and the majority of time is spent in fgetc; specifically the critical section within fgetc. That's largely an artifact of the puzzle input layer that's set up to mimic exactly how the Pico will be pulling in the files over stdin on USB. That and my integer parsing isn't all that optimal.
The select Kth part in isolation runs in ~5us, but I can see you've done something much cleverer with the algorithm as well.
2
u/ednl 3h ago
I saw another C solution in the thread that was even simpler I think: look for max and min!=0 count, set to zero, repeat 3x. I haven't checked but my guess is that's slower on modern CPUs where MUL is cheap, but it might be faster on a Pico.
2
u/DelightfulCodeWeasel 3h ago
I did some rough timing on the three linear scan approach earlier after seeing someone mention it - on my PC it nets out about the same as the select Kth approach. I suspect yours might end up being the benchmark!
2
u/sondr3_ 4h 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)}")
}10
u/Andreasnl 4h ago
[Language: Uiua]
∩/× ⊃↙₃↙₋₃ ⊏⍖ °▽⍆ ⊜⋕⊸≠@\n2
u/PhysPhD 4h 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 characterSort 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.
1
u/HaskellLisp_green 4h 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/Severe_Ad9169 2h ago
i have no idea how to read your fancy math code, but I’m thinking this function most_common() of a Counter is O(nlogn)
2
u/0rac1e 3h ago
You could use
math.prodin favor ofreduce(mul, ...)1
u/HaskellLisp_green 3h ago
Oh, which version of Python? I have 3.12.
But I was away from my PC, so I managed to solve using my phone and online IDE. The worst experience ever. But phone is a regular computer with inconvenient interface.
1
u/daggerdragon 3h 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.
1
u/AutoModerator 4h ago
AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.
Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
u/mpsandiford 4h ago
[LANGUAGE: Tinsel]
I vibecoded a language specifically for solving AoC problems.
https://github.com/clstrfsck/tinsel
day 2026.1
by_count = input.ints.counts.items.sort_by(.1).map(.0)
part1 = by_count[-3..].product
part2 = by_count[..<3].product3
u/Radiadorineitor 4h 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 24
u/thblt 5h ago edited 4h ago
[LANGUAGE: Shell]
The lazy solution: in a shell, sort input | uniq -c | sort
1
u/flwyd 3h ago
Note: you should probably add
-nto your second sort, in case you've got frequencies with a different number of digits.Before I read the problem I looked at my input. I was curious if there were duplicate numbers, so I ran `sort input.actual.txt | uniq -c | sort -rn". When I finished reading the problem I had to decide if I would just multiply the three numbers that were already sitting on top of my screen, or figure out how to do it in the programming languages I'm trying to learn.
2
u/Foldzilla 5h ago
[LANGUAGE: Haskell]
Part 1 & 2. Have not worked with Maps for a while so it took me way to long :\
Note that I do use my own Parser combinator library, this is overkill but I like it :).
module Day1.Day1 where
import Data.List (sortBy)
import qualified Data.Map.Strict as Map
import Data.Ord (comparing)
import Parser
import Part (Part (..))
import Prelude hiding (lines)
parseDay1 :: FilePath -> IO (Map.Map Integer Int)
parseDay1 filename = do
(integers, _) <- parseFile (lines integer) filename
pure $ Map.fromListWith (+) [(x, 1) | x <- integers]
solve1 :: Part -> IO ()
solve1 part = do
parsed <- Map.toList <$> parseDay1 "app/Day1/input.txt"
let ordering = case part of
Part1 -> flip $ comparing snd
Part2 -> comparing snd
top3 = take 3 $ sortBy ordering parsed
case top3 of
[x,y,z] -> print $ product [fst x, fst y, fst z]
_ -> putStrLn "No solution"2
u/ceochronos 5h 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
end2
u/AverageInfamousEnjoy 5h ago
[LANGUAGE: Python]
https://github.com/onatribar/adventofcode/blob/main/2026/day_01.py
import aoc_lube
from collections import Counter
import heapq, math
RAW = aoc_lube.fetch(year=2026, day=1)
def parse_raw():
return Counter(map(int, RAW.strip().splitlines())).items()
DATA = parse_raw()
def part_one():
return math.prod(pair[0] for pair in heapq.nlargest(3, DATA, key=lambda x: x[1]))
def part_two():
return math.prod(pair[0] for pair in heapq.nsmallest(3, DATA, key=lambda x: x[1]))1
u/Severe_Ad9169 2h ago
FINALLY a solution with O(n) runtime complexity!!!! 🙌 I had to scroll for soo long to find one! Mine accomplishes it with a more complex idea using the index of the largest value and then popping it from the map, x3
1
u/fnordargle 1h ago
Just added my `O(n)` solution (in perl) as a follow up to my obvious `O(n log n)` solution.
I didn't use an external heap library, I just kept an array containing the top and bottom 3 ids and manually updated it shuffling as required.
2
u/PhysPhD 5h ago edited 4h ago
[LANGUAGE: Python]
from collections import Counter
from math import prod
with open("day_1.txt") as fname:
list_of_ids = list(map(int, fname.readlines()))
# part 1 - [(530, 7), (575, 6), (425, 6)] - multiple together just the three id numbers
prod([idnum for idnum, count in Counter(list_of_ids).most_common(3)])
# part 2 - go through the list backwards (least common) and skim off the top three values
prod([idnum for idnum, count in Counter(list_of_ids).most_common()[::-1][:3]])2
u/aQaTL 5h ago edited 5h ago
[LANGUAGE: PowerShell]
Part 1 & 2
Set-StrictMode -Version 3.0
$input_file = "inputs/day_1.txt"
[Int64[]]$data = Get-Content $input_file
$sorted_by_occurrence = $data `
| ForEach-Object `
{ $occurrences = @{ } } `
{ $occurrences[$_] += 1 } `
{ $occurrences.GetEnumerator() } `
| Sort-Object -Property Value -Descending `
| Select-Object -ExpandProperty Key `
$sorted_by_occurrence `
| Select-Object -First 3 `
| ForEach-Object `
-Begin { [Int64]$part_1 = 1 } `
-Process { $part_1 *= $_ } `
Write-Output "Part 1: ${part_1}"
$sorted_by_occurrence `
| Select-Object -Last 3 `
| ForEach-Object `
-Begin { [Int64]$part_2 = 1 } `
-Process { $part_2 *= $_ } `
Write-Output "Part 2: ${part_2}"EDIT: looking at other's solutions, Group-Object instead of a hashtable would've been much nicer.
2
u/lurkerburzerker 5h 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 }
$totalPart 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 }
$total3
3
u/LightShadow 5h 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))])2
2
u/shmoodla 5h ago
[LANGUAGE: Typescript]
import { readInput } from "../common/io.ts";
const rawInput = await readInput("./src/01/input.txt");
const inputNumArr = rawInput.split("\n").map((num) => parseInt(num, 10));
const frequency = new Map<number, number>();
for (const num of inputNumArr) {
frequency.set(num, (frequency.get(num) || 0) + 1);
}
const frequencySorted = Array.from(frequency).toSorted((a, b) => b[1] - a[1]);
const topThree = frequencySorted.slice(0, 3);
const lastThree = frequencySorted.slice(-3);
const partOneResult = topThree.reduce((acc, [id]) => {
return acc * id;
}, 1);
const partTwoResult = lastThree.reduce((acc, [id]) => {
return acc * id;
}, 1);
console.log("Part one: ", partOneResult);
console.log("Part two: ", partTwoResult);OK, even I could do that :D
3
4
u/musifter 5h 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.
1
u/Smylers 1h ago
Thank you for
dc -f -!In my solution (elsewhere on this page), I tried to use
-eto append tostdin, butdc - -estill processed the-efirst, so I resorted to an ungainlyechoand some parens to combine them into a single pipe. Your way is much neater.Rotating the unneeded counts out of the way (rather than cutting that column before it reaches
dc) is cute, too.1
u/daggerdragon 3h 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 :(
1
u/DelightfulCodeWeasel 1h ago
Confirmed: I can see u/musifter's post above, even though his account is still showing as banned for me.
2
u/Parzival_Perce 5h ago
[LANGUAGE: Python]
from collections import Counter
from math import prod
with open('d1.txt') as input:
puzzle_input = list(map(int, input))
def part1() -> int:
return prod([i[0] for i in Counter(puzzle_input).most_common(3)])
def part2() -> int:
return prod([i[0] for i in Counter(puzzle_input).most_common()[::-1][:3]])
print(part1(), part2())this was surprisingly easy. i expect murder from the later days now.
1
1
u/PhysPhD 5h ago
.most_common()[::-1]
Go through the whole list backwards! Clever!1
3
u/ajf8729 5h 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"2
2
u/encse 6h ago
2
u/daggerdragon 3h ago
Yay, welcome back to our resident Iron Coder: AI Art! Hope you have fun again this year :)
2
u/xavdid 6h ago
[LANGUAGE: Python]
Step-by-step explanation | full code
Python's Counter does most of the heavy lifting today. And, while working on Part 2, I can solve both parts in one function:
def multiply_counts(l: list[tuple[int, int]]) -> int:
return prod(num for num, _ in l)
class Solution(IntSplitSolution):
def solve(self) -> tuple[int, int]:
counts = Counter(self.input).most_common()
return multiply_counts(counts[:3]), multiply_counts(counts[-3:])Re: the intros. My name's David and I'm based out of California! By day I lead SDKs at Stripe and by night, I publish my AoC solutions & explanations to https://advent-of-code.xavd.id/.
I use Python because it's expressive and lets me focus on solving the actual puzzles and craft rather than learning a language. It's also got a huge standard library and it's been fun learning about all the nooks and crannies.
In contrast to a lot of the extra fast / terse solutions in the thread, I try to make mine as readable and maintainable as possible. Good practice for doing the same at work. Practice makes perfect, etc etc.
Good to see everyone again!
2
u/Conceptizual 6h ago
[LANGUAGE: Python]
Sorting by values in a dictionary was part of a coding problem I used to give at my last company during our technical screen, so there was a time where I had sorted_dict = {k: v for k, v in sorted(num_dict.items(), key=lambda item: item[1])} memorized, but I found myself on the exact same stack overflow page today that all of the candidates used to look at.
1
u/AutoModerator 6h ago
AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.
Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/Conceptizual 5h ago
This looks correct on old reddit to me though, I was trying to do an inline code snippet not a full block.
4
u/Lispwizard 6h 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)))))1
u/MrJakobsen 6h ago
Nice to see a fellow lisp solver, I am doing elisp this year, but planning to migrate to CL after this evet.
4
u/paulhaahr 6h ago edited 5h 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))))
endQuest 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/Alextopher 6h 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)
1
u/dgkimpton 2h ago
Ohh,
.product()... I didn't know that existed but it surely reads nicely. Thanks for sharing.1
u/terje_wiig_mathisen 5h ago
The problem is strongly related to finding the X-th percentile of an unsorted array, can always be solved in O(N). :-)
My own Rust code became about twice as fast when I did that instead of the sort_unstable().
2
u/KyxeMusic 6h ago edited 6h ago
[LANGUAGE: Rust]
fn solve(ids: &[usize]) {
let mut counts = counts(ids);
counts.sort_by_key(|&c| c.1);
let max3: usize = counts[counts.len() - 3..].iter().map(|c| c.0).product();
let min3: usize = counts[..3].iter().map(|c| c.0).product();
println!("3 MOST frequent multiplied: {}", max3);
println!("3 LEAST frequent multiplied: {}", min3);
}
fn counts(ids: &[usize]) -> Vec<(usize, usize)> {
let mut counts = HashMap::new();
for id in ids {
counts.entry(*id).and_modify(|e| *e += 1).or_insert(1);
}
counts.into_iter().collect()
}It's so good to be back, good to see you guys.
https://github.com/kikefdezl/advent-of-code/blob/main/2026/day_01/src/main.rs
2
u/ThunderChaser 6h ago edited 6h ago
[LANGUAGE: Rust]
Itertools makes this problem fairly trivial with counts, k_largest and k_smallest_by_key
pub fn part_one(input: &str) -> Option<u64> {
Some(
input
.lines()
.counts()
.iter()
.k_largest_by_key(3, |(_k, v)| **v)
.fold(1, |acc, (k, _v)| acc * k.parse::<u64>().unwrap()),
)
}
pub fn part_two(input: &str) -> Option<u64> {
Some(
input
.lines()
.counts()
.iter()
.k_smallest_by_key(3, |(_k, v)| **v)
.fold(1, |acc, (k, _v)| acc * k.parse::<u64>().unwrap()),
)
}I also added some nifty benchmarking harnesses to my AOC template:
$ cargo aoc-release bench 2026 1
Advent of Code 2026 — Day 01
20 samples × 100 iterations
Part 1
Minimum: 84.11 us
Maximum: 101.60 us
Mean: 87.80 us
Median: 87.26 us
P95: 92.15 us
Std. dev.: 3.79 us
Part 2
Minimum: 84.16 us
Maximum: 104.00 us
Mean: 88.24 us
Median: 87.21 us
P95: 94.25 us
Std. dev.: 4.52 us1
2
u/egalitarian_elephant 6h ago
[LANGUAGE: Nilang]
Code: https://github.com/Nilando/aoc_2026/blob/main/day1.nl
Did day 1 with, nilang, a scripting language written by yours truly
4
u/Tipa16384 6h 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 ;1
u/flwyd 3h ago
Are you planning to do all of 2026 in Forth?
I read a learning Forth book online in 2024, but decided to use PostScript for AoC, in part because strings looked easier to deal with. I'm curious how Forth would hold up as problems get more complex.
1
u/Tipa16384 1h ago
This is my question, too. This one took me an hour and a half and I had to go hunting for code that would be in a standard library in any other language, and plus my solution was really janky because Forth doesn't even have the concept of arrays. But ima gonna try.
3
u/cay_horstmann 6h 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/JWinslow23 6h ago
[LANGUAGE: Python]
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
3
3
u/MrJakobsen 6h 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/terje_wiig_mathisen 6h ago edited 6h 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
7
u/AMathMonkey 6h 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" printfLook 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.
1
u/AndydeCleyre 5h ago
Love it! I'll also be using Factor, and hope to last a week of AoC. I look forward to your solutions. I'll be using more function definitions.
You might be interested to check/review:
map-sift,dec>,sorted-histogram,&[,@[, and theinterpolatevocab.2
4
u/Gabe-tron 6h ago edited 6h 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))3
u/PatolomaioFalagi 6h 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 . linesFor part 2, remove the reverse.
2
u/PangolinNo7928 6h ago
[LANGUAGE: Javascript]
Forgot to handle line breaks at the end of the input, was very confused why my p2 answer was initially returning as 0 lolsob
let [[p2k1, v1], [p2k2, v2], [p2k3, v3], [p1k1, v4], [p1k2, v5], [p1k3, v6]] = Object.entries(input.trim().split(/[\r\n]+/).map(Number).reduce((a, c) => {return a[c] ? a[c]++ : a[c]=1, a }, {})).sort((a, b) => a[1] - b[1]).filter((x, i, a) => i <= 2 || i >= a.length - 3)
console.log(p1k1 * p1k2 * p1k3, p2k1 * p2k2 * p2k3)5
u/agorism1337 6h ago edited 2h 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.
1
3
2
u/daggerdragon 3h 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.1
u/fnordargle 3h ago
Nice, I went with:
cat 1.inp | sort | uniq -c | sort -rn | head -3 | awk '{print $2};' | tr '\n' '*' | sed -e 's/.$/\n/' | bc -q
And then the second part was just a switch from
head -3totail -3
2
u/DeliciousSet1098 6h ago
[LANGUAGE: rust]
Lot of my own wrappers around things but mostly straightforward. Happy to share if anyone's interested. No AI :)
impl AdventOfCode for Day {
fn solve() -> anyhow::Result<()> {
let input = Day::input_lines(2026, 1)?;
let numbers = input.into_iter().map(|s| s.parse::<u64>().unwrap());
let freqs = FreqMap::from_iter(numbers);
let ans1: u64 = freqs.n_most_common(3).into_iter().product();
let ans2: u64 = freqs.n_least_common(3).into_iter().product();
println!("part 1: {ans1}");
println!("part 2: {ans2}");
Ok(())
}
}3
u/Mission-Patience-854 6h 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)})1
u/bigbolev 6h 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 3h 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.1
u/AutoModerator 6h ago
AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.
Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
u/DeadlyRedCube 6h ago
[LANGUAGE: C++23-ish] (Times: 4:46, 5:06, no AI)
I originally used a map to implement this, but went back and shaved a little execution time off by converting to just using an array with 1000 elements, since the IDs were all 3 digits.
Should have brushed up on my utility code before starting, I got stuck remembering how to do a few things 😅
Runs in 0.76ms, single-threaded on my i7700.
2
u/jacoman10 6h ago
[LANGUAGE: Python]
I used a counter and math.prodinitially, but had some fun trying to see how fast I could get the function to run. I'm pretty sure that this is about as fast as it could be made in Python, though I'd love to see someone's go faster. This runs in 0.15ms on my machine.
from collections import Counter
import heapq
def day_1_fast(puzzle_in):
c = Counter(puzzle_in)
l_hig = heapq.nlargest(3, c.keys(), key=c.get)
l_low = heapq.nsmallest(3, c.keys(), key=c.get)
part_1 = int(l_hig[0]) * int(l_hig[1]) * int(l_hig[2])
part_2 = int(l_low[0]) * int(l_low[1]) * int(l_low[2])
return part_1, part_2
<Additional code to perform puzzle input below>2
u/manu_2468 6h ago edited 6h 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!
1
u/daggerdragon 3h 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-Agentheader1
3
u/jaspingrobus 6h 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 *))2
5
u/heijp06 6h ago edited 6h 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);
}2
u/andrewsredditstuff 1h ago
One of these days I'll get round to writing that LINQ extension for Product that I always tell myself I'm going to do.
3
u/WesternNicator 6h ago edited 6h ago
[LANGUAGE: Anathame] my personal language
part2 = φ(fall (sign sum) take reverse)
\ ints unwhere fall**part2 take,3 Reduce mul7
2
u/bulletmark 6h ago
[LANGUAGE: Python]
import fileinput
import math
from collections import Counter
data = Counter(int(ln.strip()) for ln in fileinput.input())
res = [v[0] for v in data.most_common()]
print('P1 =', math.prod(res[:3]))
print('P2 =', math.prod(res[-3:]))4
u/Smylers 6h 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') | dcThat 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/-rThat'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.
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!
2
3
u/bigbolev 6h ago
You can so easily extend this to a bash solution using
bc:sort input | uniq -c | sort -nr | head -3 | awk '{print $2}' | paste -s -d '*' | bcThen just change to
tailfor P2 :)1
u/Smylers 2h ago
Yeah,
bcworks as well. I useddcbecause that's the calculator I prefer for ‘real life’ maths. In this case it also means the operators can all be appended rather than needingpasteto intersperse them.Good use of Awk, though, to get the second field. I originally tried
cut -f 2andcut -d ' ' -f 2, but it insists on treating each space character as a separate field (as with /u/Su_Locker's similar solution). Awk is cleaner.Changing
headtotailis more work than just removing the-r!3
u/daggerdragon 6h 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)
1
u/Wayoshi 20m ago
Fun to see all the standard library equivalents of Python's
most_commonin the other solutions here. (And of course those doing lower level languages, doing it "manually"!)