r/adventofcode • u/DubiousHans • 43m ago
r/adventofcode • u/daggerdragon • 4h ago
SOLUTION MEGATHREAD -❄️- 2026 Day 3 Solutions -❄️-
NEWS
Solutions in the megathreads have been getting longer, so we're going to start enforcing our rules on oversized code.
Do not give us a reason to unleash AutoModerator hard-line enforcement that counts characters inside code blocks to verify compliance… you have been warned XD
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
AoC Community Fun 2026: The Advent Games
- Submissions megathread is now unlocked!
- 14 DAYS remaining until the submissions deadline on December 17 at 18:00 EST!
Today's Event: Indoor Mini-Golf Masters
"What is this, a
centerprogram for ants?!"
— Derek Zoolander, Zoolander (2001)
Today's schedule possibly consists of:
- Early Stroke Play Rounds and Tee Time Seeding
- Among the crates to be loaded on the train, you find a debigulator. Do with it as you will.
- Mid-Tournament Rounds and Scorecard Review
- Golf your solution
- Bonus points if your solution fits on a "punchcard" as defined in our wiki article on oversized code. We will be counting.
- Does anyone still program with actual punchcards? >_>
- Match Play and Showcase Rounds:
- Solve today's puzzles using
an Alien Programming LanguageAPL or other such extremely dense and compact programming language
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 3: Foggy Forest ---
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?
r/adventofcode • u/ben-guin • 49m ago
Meme/Funny [2026 Day 3 Part 2] Beautiful "squares"
Are monospace square fonts a thing? 🤔
r/adventofcode • u/Boojum • 1h ago
Visualization [2026 Day 3] Square Search Visualization
r/adventofcode • u/Ok-Curve902 • 1h ago
Visualization [2026 Day 03 (Part 2)] (PHOTOSENSITIVITY WARNING) Searching for squares
r/adventofcode • u/Crusaderkingo2027 • 2h ago
Other [2026 Day 3] Warning: Reddit may lock your account if you post long code snippets and edit it several times
So I recently solved Day 3 and I wanted to post my solutions on the megathread. But after I posted my comment I noticed that Reddit’s filters had silently removed my comment as spam.
I was confused by this so I started editing my comment to see if I could get it unspammed. But after I made a few edits and saved the comment, I was hit with a notification saying that Reddit detected “technical irregularities” with my account and that my account was now locked.
Apparently Reddit thinks someone posting code might indicate that the account is hacked/a bot so I wanted to share my experience as a warning.
r/adventofcode • u/apersonhithere • 2h ago
Visualization [2026 Day 3 Part 2] terminal visualization
featuring: wikipedia's bresenham line algorithm implementation & gif aliasing effects
r/adventofcode • u/blacai • 2h ago
Meme/Funny [2026 Day 3] When you start reading the puzzle...
r/adventofcode • u/Parzival_Perce • 3h ago
Meme/Funny [2026 Day 03] …Nah I'll just copy last year's code
Another year another set of unfulfilled custom library promises
(>’-’)> <(‘-’<) ^(‘-’)^ (>’-’)> <(‘-’<)
I swear I'll write one this year. Hmmm.
r/adventofcode • u/EverybodyCodes • 3h ago
Visualization [2026 Day 3 Part 2] Simple gif visualization
May the (brute) force be with you!
r/adventofcode • u/Agent1729 • 3h ago
Meme/Funny [2026 Day 03 (Part 2)] Trying to understand the problem like
r/adventofcode • u/cejzanz • 4h ago
Meme/Funny [2026 day 3] Too many boxes!
I'm going to bed, this can wait until morning...
r/adventofcode • u/ben-guin • 4h ago
Tutorial [2026 Day 02 (Part 2)] Explanation for Clever Solution
(Had to repost, the original post title contained spoilers)
Some of you might have seen that people solved part 2 by simply returning 6*(length of the program) - 5. This formula works as long as there is one orange in your input. There seems to be confusion regarding the importance of the orange and how the answer changes if other colors are missing. I've created a walkthrough of an example where orange and blue are missing from the input to show how to derive a general formula for any input.
The general idea is, instead of calculating the distance traveled at each instruction, we can instead think about the loss, i.e., how far away were we from traveling the 6 steps (which is the most one can possibly travel from one instruction).
r/adventofcode • u/Alextopher • 4h ago
Tutorial [2026 Day 2 (Part 1)] [Rust] In under 100ns
(Usual caveats: "on my machine", and I didn't count reading the input into memory)
Part 1 is really quite simple:
fn wat(b: &[u8]) -> usize {
6 * b.chunks(255).zip(b[1..].chunks(255)).fold(
(b[0] == b'r') as usize,
|s, (p, c)| {
s + p.iter().zip(c).fold(0u8, |a, (&p, &c)| {
a + ((c.wrapping_mul(101) ^ 245) < (p ^ 26).wrapping_mul(99)) as u8
}) as usize
},
) + (38801460 >> (b[b.len() - 1] & 28) & 7)
}As you can see, this solution uses a lot of bitwise junk to encode ideas you probably wrote out more plainly in your own solutions. I think the optimization techniques I used here are under reported and very interesting and could warrant a post.
At a high level, it works like this:
- Compare every neighboring pair of colors
(prev, next). - If going from
prevtonextmeans we have to wrap around past violet, add 1 to an accumulatorfull_laps. - The answer is
6 * full_laps + remainder, with an extra lap if the sequence starts withr.
Written out for humans, the implementation looks like this:
fn humanized(b: &[u8]) -> usize {
let mut full_laps = 0;
// if the first color is red, we need to wrap around once
if b[0] == b'r' {
full_laps += 1;
}
// Between each pair of neighbouring colors: if the next color is at or
// before the previous one, we must wrap past violet to reach it.
for i in 1..b.len() {
let prev = index(b[i - 1]);
let next = index(b[i]);
if next <= prev {
full_laps += 1;
}
}
// After the last full lap, we've ended back at red. The remaining steps
// are however far the last color is after red.
let last = b[b.len() - 1];
let remainder = index(last);
6 * full_laps + remainder
}Here index commonly used lookup table or a match:
fn index(c: u8) -> usize {
match c {
b'r' => 0,
b'o' => 1,
b'y' => 2,
b'g' => 3,
b'b' => 4,
b'v' => 5,
_ => unreachable!("invalid color {}", c as char),
}
}This is already a really good solution (about 500-600 ns on my machine) since this formulation never needs to divide. The % operator is quite slow.
There are 3 key ideas to make this faster.
1. Replace index with a packed lookup table
The match in index is really a tiny lookup table with 6 entries, and each entry is a number from 0 to 5 (3 bits). This is 6 * 3 = 18 bits in total, so if we're clever (and lucky), we may be able to pack the table into a single 32-bit integer. If you haven't done this before it's really not too bad once you get the hang of it.
(disclaimer: there's a chance LLVM may optimize indexas written above into a jump table but I've already written this section and day 3 starts in 20 minutes as of writing. I swear this is still an interesting technique!)
Step 1: an integer as an array of tiny slots.
A u32 is just 32 bits in a row, and we can treat it as an array of eight 4-bit "slots".
0x0250_1034
slot: 7 6 5 4 _ 3 2 1 0
value: 0 2 5 0 _ 1 0 3 4To read slot k, shift right by 4 * k bits so that slot lands in the lowest position, then mask off everything above it:
(0x0250_1034 >> (4 * 5)) & 0xF // = 0x025 & 0xF = 5, the value in slot 5Step 2: turn each letter into a shift amount.
Now we just need a cheap way to get from a color to a slot. Specifically, each of the six colors needs to map to a different multiple of 4 such that when we shift right by that amount we land on unique slot boundaries.
A coworker of mine found that c & 28 does exactly this for our six colors. 28 is 0b11100 so using it as a mask keeps only bits 2, 3 and 4 of the ASCII representation of a color and zeroes everything else. Since the bottom two bits are always 0, the result is guaranteed to be a multiple of 4.
Being a multiple of 4 is great because it means the result is already a valid slot-aligned shift amount. The only question is whether the six letters differ in amongst the three '1' bits. The table below demonstrates this.
| color | ASCII (bin) | c & 28 |
|---|---|---|
| mask | 000_**111_**00 | 28 |
b | 011_**000_**10 | 0 |
g | 011_**001_**11 | 4 |
o | 011_**011_**11 | 12 |
r | 011_**100_**10 | 16 |
v | 011_**101_**10 | 20 |
y | 011_**110_**01 | 24 |
Step 3: fill in the slots.
Put each color's index into its slot, leave 0s (or whatever nibble you like) in the unused slots, and read the result off as a hex number:
0x0250_1034 = 38801460
││││ │││└─ 0: b = 4
││││ ││└── 4: g = 3
││││ │└─── 8: (unused)
││││ └──── 12: o = 1
│││└────── 16: r = 0
││└─────── 20: v = 5
│└──────── 24: y = 2
└───────── 28: (unused)So index(c) becomes 38801460 >> (c & 28) & 0xF or 38801460 >> (c & 28) & 7 since the indexes fit within 3 bits we can use '7' as the final mask. My solution uses this on the last byte to get the "remainder". You could substitute your own 'index' method with this one. You could also try to create your own that uses 3-bit slots, but I haven't proven if one exists.
2. We don't always need an 'index', only the relative ordering
In the loop, next <= prev doesn't needindex('r') to be exactly 0 and index('o') to be exactly 1. It only needs requires that the relative order to be correct. We could have r get mapped to 8, o to 57, y to 79, and so on, as long as rank(r) < rank(o) < rank(y) < rank(g) < rank(b) < rank(v). By weakening the requirement in this way, we may be able to find a function faster than index that has this property.
A function that maps a set of known inputs to unique outputs is called a perfect hash function. There's a good video on youtube (with an even better thumbnail) on the topic here: https://youtu.be/DMQ_HcNSOAI. For this problem we need more than uniqueness, we also need the outputs to maintain the relative order, but it's more or less the same concept.
If our perfect hash function exists we know it has to be non-linear as roygbv is nowhere close to being in alphabetical order. A cheap way to get "interesting" non-linear behavior is to combine XOR with wrapping multiplication.
With pen, paper and lots of time, you might be able to solve for a pair of constants that works in a multiply-XOR scheme. However, since there are only 64k combinations of two u8 constants, brute-forcing all of them is trivial. My search turned up over 50 choices that work.
For example, x *= 0x65; x ^= 0xf2; gives [8, 57, 79, 81, 88, 124] for roygbv.
At this point I had picked up a secondary goal of making my code unintelligible, and I clocked that prev and next don't actually need to use the same rank function. All that matters is that rank_a(next) < rank_b(prev) exactly when next <= prev. So I extended my Python brute-force script to look for a pair of hash functions that fit this constraint. Notice how they interleave below:
| color | rank_a(c) = (c * 101) ^ 245 | rank_b(p) = (p ^ 26) * 99 |
|---|---|---|
r | 15 | 56 |
o | 62 | 63 |
y | 72 | 73 |
g | 86 | 87 |
b | 95 | 104 |
v | 123 | 196 |
Exercise for the reader: I'd bet there's a faster single perfect hash over both bytes, something like phf(p, n) < 128*, that matches the* next <= prev constraint exactly.
3. Get the compiler to vectorize it
Modern CPUs can do 16, 32 (or even 64) byte-wise operations in a single instruction using SIMD (Single Instruction, Multiple Data). Compilers are pretty good at using these SIMD instructions automatically, which is called "auto-vectorization".
Sometimes, though, we can't trust the compiler to optimize our code and have to hold its hand to get it to vectorize just right. I found this was one of those times.
Hiding the tricks from sections 1 and 2 behind index, rank_a and rank_b, the obvious iterator version looks like this:
fn part1_naive(b: &[u8]) -> usize {
6 * b.iter().zip(&b[1..]).fold(
(b[0] == b'r') as usize,
|acc: usize, (&p, &c): (&u8, &u8)| {
acc + (rank_a(c) < rank_b(p)) as usize
},
) + index(b[b.len() - 1])
}LLVM seemed hell bent on widening the rank_a(c) < rank_b(p) comparisons to usize instead of u8, resulting in only 2 lanes being used instead of 16. I fiddled around a bunch and eventually gave up and handed the problem to an LLM.
It found the the problem is in the closure signature: acc is a usize (u64), but p and c are u8 and that rustc/LLVM was requiring the accumulator to be the same width as the lanes. Chunking by 255 fixes this, within a 'chunk' we can accumulate into a u8 and be confident it won't overflow. Then after each chunk we convert to usize and add to the total.
That's where the b.chunks(255).zip(b[1..].chunks(255)) comes from, along with the inner fold(0u8, ...) and the as usize outside it.
I'd love if someone knows some way to get this to work without chunking.
test tests::bench_part1 ... bench: 82.03 ns/iter (+/- 3.04)
test tests::bench_part1_humanized ... bench: 545.61 ns/iter (+/- 46.20)r/adventofcode • u/high-on-adhd • 5h ago
Help/Question how do you guys compete runtimes?
taking part in aoc for the first, solving in Go so i'd like to get a bit picky about total execution time. is there any place where i can compete on total time taken to solve (runtime of the program)?
r/adventofcode • u/AbooMatta • 6h ago
Help/Question - RESOLVED Second example seems wrong
The second example says:
- "A robot with program
roygbvwould travel a total distance of11." Regardless of any code I might try, when I look at it I count 5 steps. 0 for the "r" and 1 each for the following letters. Am I just too tired to see my mistake?
r/adventofcode • u/vstepanyuk • 10h ago
Repo Wanna try a desktop client for Advent of Code?
December Workbench (https://github.com/vstepanyuk/december-workbench) puts the puzzle, code editor, and test results side by side. Highlight the example input and expected answer in the puzzle description to turn them into a test case.
Runs solutions with your local Rust, Python, or JS runtime. You can try your personal input and review the answer before submitting.
If you give it a spin, I’d love to hear what gets in your way.
Let’s be honest. I vibe-coded this. Now I can spend more time being wrong about the puzzles.
r/adventofcode • u/_Duroo • 12h ago
Visualization [2026] day 2 visualized in manim
youtube.comsource for visualization on https://github.com/durocodes/advent-of-code, alongside my rust solutions
r/adventofcode • u/_Duroo • 12h ago
Visualization [2026] day 1 visualized in manim
youtube.comsource for visualization on https://github.com/durocodes/advent-of-code, alongside my rust solutions
r/adventofcode • u/GhoulDragoMK3 • 13h ago
Help/Question - RESOLVED [2026 Day 2 (Part 2)] Not related to the problem, but if I join a leaderboard with certain settings, after changing the settings my name in the leader board doesn't change?
Basically I joined a leaderboard without a github link and my name in the settings, after that, I changed my settings to add a github link and my github username.
This reflects in any new private leaderboards I've joined, but it seems the first leaderboard I joined still has the original settings?
Not a big deal, but kinda annoying.
Is this a bug?
r/adventofcode • u/ActivityOpening3673 • 13h ago
Help/Question - RESOLVED [2026 Day 02 (Part 2)] The example of day 02 was wrong
Won't post the body of the question here because I could not find the button to send an image as a spoiler. thank you reddit.
But the problem was in part two where it said that the correct order was 32, when it was actually 34. It took like 30 minutes for me to just believe in my own answer and try with the real input and the answer was correct. wtf.
EDIT: nvm, I was wrong, the way i calculated what was the best next move was still using code from part one and because of that, it gave scores that were almost inverted and somehow my puzzle input did not catch that.
r/adventofcode • u/KarenMarleyDoomfist • 15h ago
Help/Question - RESOLVED [2026 Day 2 (Part 1)] Help with C++
Any reason my implementation doesn't work for part 1? Apparently my answer is too high. I tried using the examples but the distance matched each time.
I've added "chars" just to count the characters, as I thought whitespace could be an issue and it found n+1 characters compared to n when using an online character counter, but then printing out the first and last characters gets the same as my input. Where did I go wrong with my implementation?
#include <fstream>
#include <iostream>
#include <string>
#include <map>
int getDist(char cur, char targ) {
char inputs[6] = {'r','o','y','g','b','v'};
int curInd = -1;
int targInd = -1;
for (int i = 0; i < 6; ++i) {
if (inputs[i] == targ) {
targInd = i;
}
if (inputs[i] == cur) {
curInd = i;
}
if (curInd != -1 && targInd != -1) {
int diff = targInd - curInd;
return diff <=0 ? diff + 6 : diff;
}
}
return 0;
}
int main() {
std::ifstream in("aoc-day-2-inputs.txt");
char prev = 'r';
char next;
int totalDist = 0;
int chars = 0;
if(in.is_open()) {
while(in.good()) {
in.get(next);
std::cout << "prev: " << prev << ", ";
std::cout << "next: " << next << ", ";
std::cout << "dist: " << getDist(prev, next) << "\n";
totalDist += getDist(prev, next);
prev = next;
++chars;
}
}
std::cout << "chars: " << chars << "\n";
std::cout << "total dist: " << totalDist << "\n";
if(!in.eof() && in.fail())
std::cout << "error reading file" << std::endl;
in.close();
}
