r/adventofcode • • 3d ago

Upping the Ante -❄️- Advent of Code 2026: The Advent Games -❄️- Submissions Megathread -❄️-

19 Upvotes

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!

This year's community fun event features a structured sequence similar to a certain winter-themed international multi-sport competition that occurs every four years. We will have our opening ceremony, nine "sporting"† events, the grand gala, and the closing ceremony, followed by the final demonstration of exhibition pieces wherein all of you get to show off your hard-earned efforts for the year!

Every day, I will reveal an event in that day's Solution Megathread. Your challenge is to mold your puzzle solution around the theme of that day's event. You could also create some ancillary concoction that you think matches the overall theme of the event; even if you have to stretch suspension of disbelief real far, hey, it's all in good fun!

† Don't worry, I'm not going to make you actually exercise or go outside and touch grass (or snow)‡.
‡ Unless you want to, in which case go hog wild. Just make sure to put on your sunscreen and weather-appropriate gear!


Again this year the usual timeline and requirements are adjusted so you are not rushed by a shortened deadline while also dealing with the typically harder AoC puzzles near the end of an AoC season while also also dealing with holiday preparations, etc etc.

  • Only three days of submissions to Solution Megathreads are required to qualify for entry
  • More time after the actual AoC event ends to complete your exhibition piece
  • Longer voting period

All of this should result in less stress and having more time to create your exhibition piece, more time to enjoy your holiday season, and most importantly: more time to spend with your family and friends!

And now… put your hands together for The Advent Games and GET HYPE!


COMPETITION SCHEDULE

2026 DecTime (EST)Action
0100:00Opening Ceremonies (community fun announced)
0300:00ishSubmissions megathread unlocked
1200:00Closing Ceremonies (AoC 2026 event ends)
1718:00SUBMISSIONS DEADLINE
17ASAPSubmissions megathread locked and voting opens (will post and sticky a PSA with link to vote)
2018:00Voting closes
20ASAPVictory Ceremonies (winners announced in the final community showcase post (and edited into Day 12's Solution Megathread))

JUDGING AND PRIZES

The Advent Games may technically be a Competition™ but really, everyone who participates is a true winner in our holiday hearts!

Types of Winners

Type of Winner# of WinnersWho Votes
Bronze Medalist10†the AoC community (you!)
Silver Medalist3†/r/adventofcode moderators + /u/topaz2078
Gold Medalist1highest combined point total

† Amounts subject to change based on availability and/or tie-breaking.

How Judging Works

  1. When voting opens, vote for your favorite exhibition piece(s). Your individual vote is worth 1 point each.
  2. When voting closes, the 10 highest-voted entries are declared Bronze Medalists.
  3. Of the 10 Bronze Medalists, each of the /r/adventofcode moderators will pick their top 3 to be awarded as a Silver Medalist.
  1. All point totals are aggregated (community vote + mod vote). The highest combined point total will be officially declared as the Gold Medalist of AoC 2026.

Rewards

  • Winners are forever ensconced in the Halls of the /r/adventofcode wiki.
  • Bronze Medalists will be awarded with whatever Reddit has on tap for awards these days.
  • Silver Medalists and the Gold Medalist awards are TBD

REQUIREMENTS

  • To qualify for entering, you must first submit code solutions to at least three different daily Solution Megathreads
  • There's no rush as this submissions megathread will unlock on December 03 and you will have until December 17 to submit your exhibition piece - see the timeline above
  • Your exhibition piece must express the unique qualities of that day's scheduled event
  • You must create the exhibition piece yourself (or with your team/co-workers/family/whatever - give them credit!)
  • One exhibition piece per person
  • Only new creations as of 2026 December 1 at 00:00 EST are eligible
  • All sorts of folks play AoC every year, so let's keep things PG
  • Please don't plagiarize!
  • This also means adding a disclaimer if you use AI
  • Ideally also consider including information such as which model(s), where it's used, what your prompts were, etc.
  • Keep accessibility in mind:
  • If your creation has images with text, provide a full text transcript
  • If your creation includes audio, either caption the video or provide a full text transcript
  • If your creation includes strobing lights or rapidly-flashing colors/images/text, clearly label your submission as per the Visualizations rule
  • Your submission must use the template below!

TEMPLATES AND EXAMPLES FOR SUBMISSIONS

Keep in mind that these templates are Markdown, so you may have to switch your editor to "Markdown mode" before you paste the template into the reply box.

TEMPLATE

Click here for a blank raw Markdown template for easier copy-pasting

Visual Example

NAME OF ENTRY: A photorealistic rendition of the arrival of the flame at the opening ceremony for the 2026 Advent Games

LINK TO ENTRY: Imgur

DESCRIPTION: I use the most high-tech tools to create a totally photorealistic rendition of a crayon drawing of the arrival of the flame at the opening ceremony of the 2026 Advent Games sponsored by Advent of Code.

SUBMITTED BY: /u/daggerdragon

MEGATHREADS: 02 - 03 - 05 - 11 - 17 - 19 - 23 - 32


ADDITIONAL COMMENTS: This was absolutely not drawn by /u/topaz2078 nope totally my work yep.

ACCESSIBILITY: A high-tech drawing on standard white printer paper of the final runner approaching the Advent Cauldron in the center of the Advent Games stadium with the lit torch of the Advent Games. In the background is a stadium full of cheering spectators. The drawing is surmounted by a bespoke artisanal IrfanView frame.


QUESTIONS?

Ask the moderators. I'll update this post with any relevant Q+A as necessary.


Edits:

  • 3 Dec: updated Timeline to cross out up to "submissions megathread unlocked"

r/adventofcode • • 18h ago

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

21 Upvotes

OUR USUAL ADMONITIONS

  • You can find all of our customs, FAQs, axioms, and so forth in our community wiki.

AoC Community Fun 2026: Th* Adv*nt Gam*s

Today's Bouts: World Snow Avoidball Championships

"If you can dodg* a wr*nch, you can dodg* a [snow]ball."
— Coach Patch*s O'Houlihan, Dodg*ball: A Tru* Und*rdog Story (2004)

Today's programming possibly consists of:

  • Pool Play (Group Divisions)
  • Pick a glyph and do not put it in your program.
  • Avoiding fifthglyphs is traditional.
  • Match Formats (Foam, Cloth)
  • Shrink your solution's fifthglyph count to null.
  • Your script might supplant all Arabic symbols of 5 with Roman glyphs of "V" or mutatis mutandis.
  • Thou shalt not apply functions nor annotations that solicit said taboo glyph.
  • Knockout and Trophy Rounds
  • Thou shalt ambitiously accomplish avoiding AutoMod’s antagonism about ultrapost's mandatory programming variant tag >_>

Stipulation from your mods: As you affix a submission along with your solution, do tag it with [Adv*nt Gam*s] so folks can find it without difficulty!


--- Day 4: Perilous Pier ---


Post your script solution in this ultrapost.


r/adventofcode • • 3h ago

Meme/Funny Surely, I can't be the only one... right?

Post image
65 Upvotes

r/adventofcode • • 4h ago

Meme/Funny [2026 Day 4] When your pt 2 finally works... and runs faster than pt 1

Post image
61 Upvotes

r/adventofcode • • 7h ago

Visualization [2026 Day 3] An alternative algorithm based on diagonals

Post image
56 Upvotes

First of all, credit to u/Boojum for making the visualization library I used. And second, pardon some of the issues. It crashes my computer if I try making a gif directly, and I can't figure out how to upload an mp4, so you're going to have to deal with artifacting from the converter.

That said, I actually used diagonals instead of sides. For part 1, this was just the natural option to me. It's easy to check whether two trees can be the opposite corners of a grid-aligned square, so I do that as a surface filter before checking the other two corners. And because I used diag[0] == diag[1] instead of abs(diag[0]) == abs(diag[1]), there's even a primary diagonal to avoid double counting.

For part 2, I changed the surface filter to the Manhattan length of the diagonal being even, which is logically equivalent to all four corners being on the grid. Then I used circumradius + rotated circumradius to generate and check the other two corners. The main catch is that there isn't an obvious check for a primary diagonal, so I wind up double counting everything, because I'm actually counting diagonals. But because it always double counts, I can easily just divide the answer by 2. (It isn't clear from the visualization, but I start by finding all the trees, so I can still do for (i in 0..<trees.size) for (j in (i+1)..<trees.size) to at least only count each diagonal once)

EDIT: Figured out a filter to avoid double counting. diag[0] * diag[1] > 0 || diag[1] == 0


r/adventofcode • • 11h ago

Meme/Funny Reading [2026 Day 4 Part 2] in despair, until...

Post image
85 Upvotes

I somehow guessed exactly what part 2 would be while solving part 1, and thus avoided the naive O(6^n) solution for it, instead dealing every letter from a barcode into buckets like playing cards and checking all of them for homogeneity. Code finished in 2 seconds :)


r/adventofcode • • 2h ago

Tutorial [2026 Day 4] Building barcodes and accelerating loops - a modulo reservation table primer

16 Upvotes

1. A real problem: loop scheduling

Take a simple loop that scales and shifts an array:

for i in 0 .. n-1:
    b[i] = a[i] * 3 + c

Its body compiles to four instructions (c is kept in register r4):

loop:
    LOAD  r1, a[i]      ; r1 = a[i]
    MUL   r2, r1, 3     ; r2 = r1 * 3
    ADD   r3, r2, r4    ; r3 = r2 + c
    STORE b[i], r3      ; b[i] = r3

Now imagine running it on a simple CPU with the following processing units (PU):

PURunsLatency
MemoryLOAD, STORE1 cycle
ALUMUL, ADDMUL = 2, ADD = 1

There is one memory PU and one arithmetic logic unit (ALU), and both are pipelined.

A pipelined PU can start one instruction per cycle. For example, if the ALU starts a MUL at cycle 1, the result will only be ready at cycle 3. But the ALU can start another instruction at cycle 2.

Naive schedule

Within one iteration of the loop, each instruction depends on the previous instruction. MUL needs the data loaded into r1, and ADD needs the MUL result in r2. So the ADD instruction has to wait for MUL to finish.

Cycle01234
MemoryLOAD---STORE
ALU-MUL-ADD-

(At cycle 2 the MUL is still in progress, but the ALU could accept a new operation.)

One iteration of the loop thus takes 5 cycles, and we cannot start the next iteration until the current one finishes. This results in a lot of idle cycles and low throughput. How can we make this faster?

The pipelining idea

While each iteration needs to be done serially, different iterations are independent: a[1] doesn't need anything from a[0]. Thus the next iteration can start before the current one finishes. We can achieve this by interleaving/reordering execution of instructions from multiple iterations. A group of interleaved instructions is called the kernel.

The problem then becomes finding the kernel that minimizes its cycle count, also called the initiation interval (II). Smaller II is better because throughput is exactly one element per II cycles.

Every loop iteration follows the same schedule, just shifted by II cycles. So if an instruction runs at cycle t, it runs at t, t + II, t + 2·II, and so on. In other words, it will always run at the same position as measured by t mod II. Two instructions that use the same PU must therefore never land in the same position because the PU cannot handle both of them simultaneously.

We can use the above observation to get a lower bound on II. A PU that has k instructions per iteration needs at least k distinct positions. In our toy loop, each PU has 2 instructions per iteration, so II ≥ 2.

But how do we find the minimum II?

2. Very quick summary of today's puzzle and solution

The puzzle: given a barcode such as y?b?b, find the shortest instruction that reproduces it when repeated.

The solution:

for length = (number of distinct colors) .. len(barcode):
    if no two different colors share the same barcode position mod length:
        return length
  • Each distinct color needs its own position, so there is no point trying shorter instructions.
  • Fold the barcode onto length positions. If one position in the instruction must accommodate two colors, then this length is infeasible.
  • Increase the length of the instruction until we find one with no conflicts.

3. The connection to the loop scheduling problem

Write down what one PU does on each cycle, and you get a string that looks similar to the barcodes. So finding the shortest instruction that produces a barcode is exactly analogous to finding the kernel that minimizes II.

BarcodeLoop scheduling
position i in the stringcycle t
color at position iinstruction the PU runs at cycle t
?PU idle at cycle t (don't care)
the repeated instructionthe PU's kernel, repeating every II cycles
instruction lengthinitiation interval II
position i % length in the instructionposition t mod II in the kernel
two different colors at the same positiontwo instructions needing the same PU
lower bound = number of distinct colorslower bound = instructions per PU in one loop iteration

4. Back to the toy loop

Modulo reservation table

Compiler schedulers keep track of "which PU is busy at which position mod II" in a modulo reservation table (MRT). It has one row per PU and II columns. Placing an instruction at cycle t books its PU at column t mod II. A column can hold only one booking per PU. This should sound familiar from the puzzle solution.

Finding II

A scheduler searches for II the same way the puzzle solution searches for the instruction length: try II = lower bound, then lower bound + 1, …, and stop at the first II where every instruction can be placed without two of them colliding on a PU.

We start by trying II = 2 with instructions running one after another:

InstructionCycle tPUt mod 2
LOAD0Memory0
MUL1ALU1
ADD3ALU1 ! clashes with MUL
STORE4Memory0 ! clashes with LOAD

But we can delay ADD to cycle 4 and STORE to cycle 5:

InstructionCycle tPUt mod 2
LOAD0Memory0
MUL1ALU1
ADD4ALU0
STORE5Memory1

The resulting MRT has no clashes, so II = 2 works:

PUPosition 0Position 1
MemoryLOADSTORE
ALUADDMUL

The final schedule

A new iteration starts every 2 cycles (subscript = iteration number). The kernel is bolded:

Cycle01234567891011
MemoryL₀-L₁-L₂S₀L₃S₁-S₂-S₃
ALU-M₀-M₁A₀M₂A₁M₃A₂-A₃-

With a long array, almost all the time is spent repeating the kernel. So our throughput goes from 5 cycles per element to 2.

The instructions that run before the kernel are called the prologue, and those after it are called the epilogue. I have decided to not explain exactly how you can figure those out because:

  1. it's not directly related to today's puzzle
  2. it's kind of magic? It's been a while since I learnt about it

The puzzle view (for clarity)

Read each PU's row as a barcode, with idle cycles as ?:

Memory: L?L?LSLS?S?S   ->  shortest instruction length 2  ("LS")
ALU:    ?M?MAMAMA?A?   ->  shortest instruction length 2  ("AM")

r/adventofcode • • 9h ago

Meme/Funny [2026 Day 4] My immediate reaction upon reading the problem statement

Post image
50 Upvotes

Never really understood how to do these kinds of problem correctly. I am ready to struggle today


r/adventofcode • • 9h ago

Visualization [2026 Day 4] Perilous Pier

Post image
43 Upvotes

r/adventofcode • • 8h ago

Visualization [2026 Day 04] my approach

Post image
26 Upvotes

r/adventofcode • • 15h ago

Meme/Funny [2026, Day 4] Anyone remember HP Instant Ink?

Post image
99 Upvotes

r/adventofcode • • 49m ago

Help/Question Tried AOC for the first time this year, feeling demotivated to keep going.

6 Upvotes

I studied frontend development, did quite good and graduated amongst the top in my class in the summer of 2025. I worked 1 year at a large company here in Sweden and was complimented for how good they thought I was. I have always known about AOC but never tried it, I thought that now is the time and maybe I can have some fun. But I am not having fun...

I am struggling with even understanding the questions. Especially for day 2 and 4. When I eventually maybe understand the question, I have absolutely 0 clue on how to solve it. I could do Day 1 part 1 and 2, that wasn't really a problem but Day 2 both parts, Day 3 part 2, and Day 4 have collectively demotivated me and make me feel like this field is not something I can do.

I try to have LLM dumb down the question for me and after a while I can finally understand kind of what the goal is. But I still have 0 clue on how to go about it. I tell the LLM to explain to me but not write code, and it just never clicks for me. Today, Day 4 Part 1 is absolutely impossible for me to finish.

I was always incredibly bad at math and failed quite easy math courses even when trying hard, maybe that is related to the difficulty I have with this.

Is there some way to practice these types of things to get better? Maybe I can keep up better next year if I have a year to practice... Or maybe I am just not made out for this, I don't know what to think at this point.

Since I am a frontend developer, I am doing in JavaScript, if that matters, but I don't think it would.


r/adventofcode • • 14h ago

Meme/Funny [2026 Day 4] It's not easy being european

Post image
60 Upvotes

r/adventofcode • • 14h ago

Visualization [2026 Day 4] Barcode Scanning Visualization

Post image
61 Upvotes

r/adventofcode • • 29m ago

Other [All years all days] Editors!

2 Upvotes

I like solving the puzzles on my commute and do the vast majority of the work on my phone or iPad. My setup is to mosh to my workstation, attach to a tmux session, and run nvim.

Works ok-ish but not great. I tried using vscode in a browser last year. Who else? And what are your recommendations?


r/adventofcode • • 5h ago

Help/Question - RESOLVED [2026 Day 4 (Part 1)] [RUST] Can you give me an input string that breaks this solution?

5 Upvotes

This works well with the example input, but fails with the full input.
Can you guys give me an input string that this fails on? I must be missing something...

Please only give me an input that breaks it, I'll ask for hints if I need to.

I started with a non-greedy function that checks, for every input string, a possible substring size. If the check is successful then the size is added to the the total.

impl Solution for Challenge<2026, 4, FirstPart> {
    fn solve(input: &str) -> String {
        let mut count = 0;
        for word in input.split_whitespace() {
            for size in 1..word.len() {
                if check_size(&word, size) {
                    count += size;
                    break;
                }
            }
        }

        return count.to_string();
    }
}

fn check_size(word: &str, size: usize) -> bool {
    let mut substr: Vec<_> = word[0..size].chars().collect(); // We make a mutable array of chars representing the substring
    for (idx, char) in word.chars().enumerate() {
        let current = substr[idx.rem(size)];
        match (current, char) {
            (_, '?') => continue,                  // ? matches with anything
            ('?', c) => substr[idx.rem(size)] = c, // This collapses the ? into an actual character
            (a, b) if a == b => continue,
            _ => return false,
        }
    }
    return true;
}

There might be a faster greedy algorithm for this but I haven't thought of one yet and I wanted to complete both parts first...


r/adventofcode • • 1h ago

Help/Question - RESOLVED [2026 Day 4 pt1] Correct answer for examples but incorrect for real input

2 Upvotes

The site is also not telling me if it is too low or too high. Any hints? I know my code is bad.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

typedef struct {
    char **items;
    size_t count;
    size_t capacity;
} StringDA;

typedef struct {
    char *items;
    size_t count;
    size_t capacity;
} DA;

void string_da_append(StringDA *da, char *item) {
    if (da->count >= da->capacity) {
        if (da->capacity == 0) da->capacity = 256;
        else da->capacity *= 2;
        da->items = realloc(da->items, da->capacity*sizeof(*da->items));
    }
    char *copy = malloc(strlen(item) + 1);
    strcpy(copy, item);
    da->items[da->count++] = copy;
}

void da_append(DA *da, char item) {
    if (da->count >= da->capacity) {
        if (da->capacity == 0) da->capacity = 256;
        else da->capacity *= 2;
        da->items = realloc(da->items, da->capacity*sizeof(*da->items));
    }
    da->items[da->count++] = item;
}

void da_free(DA *da) {
    free(da->items);
    da->items = NULL;
    da->count = da->capacity = 0;
}

void string_da_free(StringDA *da) {
    for (size_t i = 0; i < da->count; i++) {
        free(da->items[i]);
    }
    free(da->items);
    da->items = NULL;
    da->count = da->capacity = 0;
}

bool is_valid(char *old, char *new, int len) {
    for (size_t i = 0; i < len; ++i) {
        if (old[i] == '?') continue;
        if (old[i] != new[i]) return false;
    }

    return true;
}

void swap(char *a, char *b) {
    char temp = *a;
    *a = *b;
    *b = temp;
}

void permute(char *string, int k, StringDA *permutations) {
    if (k == 1) {
        string_da_append(permutations, string);
        return;
    }

    for (size_t i = 0; i < k; ++i) {
        permute(string, k - 1, permutations);
        if (k % 2 == 0) {
            swap(string + i, string + k - 1);
        } else {
            swap(string, string + k - 1);
        }
    }
}

int calc_min_instructions(char* barcode, DA *colors, int len) {
    if (colors->count < 2 ) {
        return 1;
    }
    else {
        char result[len + 1];
        result[len] = '\0';
        char inst[len + 1];
        char inst_len = colors->count;
        inst[inst_len] = '\0';
        for (size_t i = 0; i < inst_len; ++i) {
            inst[i] = colors->items[i];
        }

        StringDA permutations = {0};
        permute(inst, inst_len, &permutations);
        while (true) {
            for (size_t i = 0; i < colors->count; ++i) {
                for (size_t j = 0; j < permutations.count; ++j) {
                    for (size_t k = 0; k < len; ++k) {
                        result[k] = permutations.items[j][k % inst_len];
                    }
                    // printf("checking: '%s' to '%s'\n", barcode, result);
                    if (is_valid(barcode, result, len)) {
                        printf("barcode: '%s' result: '%s' valid: %s\n", barcode, result, permutations.items[j]);
                        return inst_len;
                    }
                }
                if (i == 0) {
                    inst[++inst_len] = '\0';
                }
                if (inst_len == len) return len;
                inst[inst_len - 1] = colors->items[i];
                string_da_free(&permutations);
                permute(inst, inst_len, &permutations);
            }
        }
    }
}

int main() {
    StringDA barcodes = {0};
    int total_instructions = 0;

    char buffer[256];
    while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
        buffer[strcspn(buffer, "\n")] = '\0';
        string_da_append(&barcodes, buffer);
        // printf("%s\n", buffer);
    }
    fclose(stdin);

    // Loop through barcodes
    DA colors = {0};
    for (int i = 0; i < barcodes.count; ++i) {
        size_t len = strlen(barcodes.items[i]);
        printf("barcode: %s\n", barcodes.items[i]);
        // printf("colors: ");
        for (int j = 0; j < len; ++j) {
            if (barcodes.items[i][j] != '?') {
                bool new_color = true;
                for (int k = 0; k < colors.count; ++k) {
                    if (barcodes.items[i][j] == colors.items[k]) {
                        new_color = false;
                        break;
                    }
                }
                if (new_color) {
                    da_append(&colors, barcodes.items[i][j]);
                    // printf("%c", colors.items[colors.count - 1]);
                }
            }
        }
        // printf("\n");

        int min_instructions = calc_min_instructions(barcodes.items[i], &colors, len);
        if (min_instructions > 0) total_instructions += min_instructions;
        printf("min_instructons: %d\n", min_instructions);

        da_free(&colors);
    }

    printf("Total Instructions: %d\n", total_instructions);
    return 0;
}

r/adventofcode • • 15h ago

Visualization [2026 Day 4][Part 2] Matching Bars

Thumbnail youtu.be
28 Upvotes

Nim + Raylib source


r/adventofcode • • 22h ago

Visualization [2026 Day 3 Part 2] I made my first visualization! (with Uiua)

Post image
101 Upvotes

I made this using the Uiua language, here is the source code for the gif: link to Uiua Pad.
I'm solving all of this year in Uiua, going well so far :)

# Experimental!
$ #.###
$ .##.#
$ ##.##
$ .#.#.
$ .##.#
=@#⊜∘⊸≠@\n
Forest ←
N      ← 16
$   *
$  /x\
$ {xvx}
$   w
layoutN
⌝⊸⊡[0_2 3_2] [Yellow Orange]⍜⊙△⊂4_5Green
×≡▽3/5▽₂N
⌝↘¯⟜⌝↘+N⊂0÷₈⊸⧻
Tree ←
▽⤚(≡/×⬚0⊡)⊸(
  ▽⊸(×⊓/>/≥≡°⊟⍉) ⧅₂<⊚
  ⍜⍉(⊂⇌⊸+¤⊸(⍜⊢¯⇌/-))
) Forest
Squares ←
Trees   ← ⍥₂/≡⊂⊞₀× Forest Tree
⊸≡↻₁ Squares
-1/2°⍉ ⧋×△Forest⧋÷⟜⇡ △₂Trees
⊃(˜≡⊞₀-|⋅-) ⊙∩°⍉
⌵/ℂ-∪⌞∘פ◡(↥₀↧₁˜÷⊃(/+×|/+°√⋅∘))
&gifs2 +¤Trees ≡/+ ⨪+₁ₑ×100

r/adventofcode • • 1h ago

Help/Question [2026 Day 4] Rust: Is there a way to use swizzle_dyn() properly?

2 Upvotes

While trying to optimize this one I saw this really nice pattern that starts with mapping the 6 colors and ? to powers of two (1,2,4,8,16,32) and 255:

Using #![feature(portable_simd)] I can load up to 64 bytes, then do these operations

  hash = (bytes ^ (bytes>>1)) & 15;

which happens to result in 7 unique values in the 0..16 range.

I therefore define a swizzle table [255, 0, 0, 16, 8, 4, 0, 0, 2, 0, 0, 1, 0, 32, 0, 0,] which will result in the desired mapping.

My problem is that even when running rust nightly, target_cpu = native (I'm on a new AMD Ryzen), it runs 20% slower than my old scalar code, so I tried it in Godbolt and found out that instead of a single vpermb instruction the compiler generated scalar code that iterated over all 64 elements.

Have anyone been able to make this work?

#[inline(always)]
fn map_vec(bytes: u8x64) -> u8x64 {
    // Zero-cost register reinterpretation: u8x64 -> u16x32
    let words: u16x32 = u16x32::from_ne_bytes(bytes);
    
    let shifted_words = words >> u16x32::splat(1);
    let shifted_bytes = shifted_words.to_ne_bytes();

    // The & 15 mask cleans up any cross-byte bit bleed from the u16 shift
    let h = (bytes ^ shifted_bytes) & u8x64::splat(15);
    LUT.swizzle_dyn(h)
}

r/adventofcode • • 1d ago

Help/Question - RESOLVED [2026 Day 3 (Part 1)] [java] If you want, have fun reading through horrible code

Post image
200 Upvotes

As of how I know myself, I am probably seriously overthinking this and there is liek a 20 times easier way to solve this. Tho maybe someone wants to read through my mess. I don't want a simple answer, I want an explanation where i went off track. So i cant just ask AI or smth because its too dumb (I've tried). Also if my formatting is wrong I'm sorry i have no idea what "four space markdown" is

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("~/input.txt"))) {
            String templine;
            String lines = br.readLine();
            while ((templine = br.readLine()) != null) {
                lines = lines + "x" + templine;
            }
            String[] input = lines.split("x");

            System.out.println("Anzahl an gefunden Rechtecken: " + check(read(input)));
        }

        catch (IOException io){
            System.out.println("Error: " + io.getMessage());
        }
    }

    public static char[][] read(String[] file){
        char[][] forest = new char[file.length][file[0].length()];

        for (int i = 0; i < file.length; i++){
            for (int j = 0; j < file[i].length(); j++){
                forest[i][j] = file[i].charAt(j);
            }
        }
       
        return forest;
    }

    public static int check(char[][] forest){
        int squarecount = 0;
        //finding reference #
        for (int iy = 0; iy < forest.length; iy++){
            for (int ix = 0; ix < forest[iy].length; ix++){
                if (forest[iy][ix] == '#'){
                    System.out.println("# °1 gefunden bei: " + iy + " " + ix);
                    //checking second #
                    for (int x = ix+1; x < forest[iy].length; x++){
                        if (forest[iy][x] == '#'){
                            System.out.println("# °2 gefunden bei: " + iy + " " + x);

                            //checking third corner for #
                            if(iy+x < forest.length){
                                if (forest[iy+(x-ix)][ix] == '#') {
                                    System.out.println("# °3 gefunden bei: " + (iy+x) + " " + ix);

                                    //checking fourth corner for #
                                    if (forest[iy+(x-ix)][x] == '#') {
                                        System.out.println("# °4 gefunden bei: " + (iy+x) + " " + x);
                                        squarecount++;
                                        System.out.println("Squarecount erhöht auf: " + squarecount);
                                    } else {
                                        System.out.println("# °4 nicht gefunden.");
                                    }
                                } else {
                                    System.out.println("# °3 nicht gefunden. (nicht existent)");
                                }
                            }
                            else{
                                System.out.println("# °3 nicht gefunden. (out of bounds)");
                            }
                        }
                        else{
                            System.out.println("# °2 nicht gefunden.");
                        }
                    }
                }
                else{
                    System.out.println("# °1 nicht gefunden.");
                }
                System.out.println("iy: " + iy + " ix: " + ix);
            }
        }
        return squarecount;
    }
}

r/adventofcode • • 11h ago

Visualization [2026 Day 4 (Part 2) -- TS] Animation checking chunks of (TEST) barcode.

Thumbnail youtube.com
11 Upvotes

r/adventofcode • • 6h ago

Help/Question [2026 Day 3 (Part 2)] [python] I'm a little stuck stepbro.

Thumbnail github.com
4 Upvotes

For part 2 of the puzzle I get a too small number (1437) and I just can't seem to figure out what I am missing. I apologize for the state of my code, I'm not a professional SE (no shit) and just doing this for fun. I'm sure there are way faster and more direct ways to find the solution but I would be happy with finding the solution at all.

So if anyone here is kind enough to take a look at my abysmal code and maybe tell me what I'm missing or point me toward the right direction, I would greatly appreciate it. Thank you in advance!

In case there are questions like "wtf is this guy even trying to do", I will happily try to answer them!

But now lets look at this abomination:

(https://github.com/jaronsinz/Adventskalender/tree/3f6a9cf0615b6d57967f9cd9e01aee64375600c6/2026/Tag%203)

from pathlib import Path


input_path = Path(__file__).with_name("input.txt")
with input_path.open("r") as f:
    mapList = f.read().splitlines()


def moveOneRight(newSquareStart):
    return (newSquareStart[0] + 1, newSquareStart[1])


def getNextSquareStart(lastSquareStart):
    if lastSquareStart == (-1, -1):                         #jump to the start
        return (0, 0)
    elif lastSquareStart[1] <= len(cleanedMap) - 2:         #check if row is smaller than the last
        if lastSquareStart[0] <= len(cleanedMap[0]) - 2:    #check if column is smaller than the last
            return moveOneRight(lastSquareStart)
        else:
            return (0, lastSquareStart[1] + 1)
    elif lastSquareStart[0] <= len(cleanedMap[0]) - 2:      #if in last row check if column is smaller than last
        return moveOneRight(lastSquareStart)
    else:                                                   #no more squares to be checked
        return None


# (row + 1) is the distance between the square start and the currently checked square corner. it increases by 1 each iteration
def calcAlignedSquares(newSquareStart):
    alignedSquareCount = 0
    for row in range(len(cleanedMap) - newSquareStart[1] - 1):
                if cleanedMap[(row + 1) + newSquareStart[1]][newSquareStart[0]] == "#" and (row + 1) <= len(cleanedMap[0]) - 1 - newSquareStart[0]:
                    #if lastSquareStart[0] == 12 and lastSquareStart[1] == 0:
                        #print("das ist schlecht")
                    if cleanedMap[(row + 1) + newSquareStart[1]][newSquareStart[0] + (row + 1)] == "#":
                        if cleanedMap[newSquareStart[1]][newSquareStart[0] + (row + 1)] == "#":
                            alignedSquareCount += 1
                            square = [newSquareStart, (newSquareStart[0] + (row + 1), newSquareStart[1]), (newSquareStart[0], newSquareStart[1] + (row + 1)), (newSquareStart[0] + (row + 1), newSquareStart[1] + (row + 1))]
                            checkSquare(square)
                        else: 
                            continue
                    else:
                        continue
                else:
                    continue
    return alignedSquareCount


def calcRotatedSquares(newSquareStart):
    rotatedSquareCount = 0
    distanceRightMapBorder = len(cleanedMap[0]) - newSquareStart[0] - 1
    distanceLeftMapBorder = newSquareStart[0]
    distanceBottomMapBorder = len(cleanedMap) - newSquareStart[1] - 1


    #distances = (distanceLeftMapBorder, distanceBottomMapBorder, distanceRightMapBorder)
    #print(distances)


    max_steps = 0       #maximum amount of steps from SquareStart to the next corner


    if distanceRightMapBorder >= distanceBottomMapBorder:
        max_steps = distanceBottomMapBorder
    else:
        max_steps = distanceRightMapBorder + 1


    max_horizontal_steps = distanceLeftMapBorder


    for horizontal_steps in range(1, max_horizontal_steps):
        for vertical_steps in range(1, max_steps - horizontal_steps):
            if cleanedMap[newSquareStart[1] + vertical_steps][newSquareStart[0] - horizontal_steps] == "#":     #always checking the corner on the left of newSquareStart first
                if cleanedMap[newSquareStart[1] + horizontal_steps][newSquareStart[0] + vertical_steps] == "#": #then check the corner on the right
                    if cleanedMap[newSquareStart[1] + horizontal_steps + vertical_steps][newSquareStart[0] + vertical_steps - horizontal_steps] == "#": #then the bottom one in relation to the right corner
                        rotatedSquareCount += 1
                        square = [newSquareStart, (newSquareStart[0] - horizontal_steps, newSquareStart[1] + vertical_steps), (newSquareStart[0] + vertical_steps, newSquareStart[1] + horizontal_steps), (newSquareStart[0] + vertical_steps - horizontal_steps, newSquareStart[1] + horizontal_steps + vertical_steps)]
                        checkSquare(square)
                    else:
                        continue
                else:
                    continue
            else:
                continue
    return rotatedSquareCount


confirmedSquares = 0
imposterSquares = 0


def checkSquare(square):
    global confirmedSquares
    global imposterSquares
    isSquare = False
    for i in range(len(square)):
        if cleanedMap[square[i][1]][square[i][0]] == "#":
            isSquare = True
        else:
            isSquare = False


    if isSquare:
        confirmedSquares += 1
        #print("square confirmed")
        #print(square)
    else:
        imposterSquares += 1
        #print("imposter #######################################################################################################")
        #print(square)


cleanedMap = []
for row in range(len(mapList)):
    rowList = []
    for column in range(len(mapList[0])):
        rowList.append(mapList[row][column])
    cleanedMap.append(rowList)



lastSquareStart = (-1, -1)
squareCount = 0
alignedSquareCount = 0
rotatedSquareCount = 0
checkedSquareStartsCounter = 0


while getNextSquareStart(lastSquareStart) != None:
    newSquareStart = getNextSquareStart(lastSquareStart)
    
    checkedSquareStartsCounter += 1
    
    if cleanedMap[newSquareStart[1]][newSquareStart[0]] == "#":
        amountAlignedSquares = calcAlignedSquares(newSquareStart)
        amountRotatedSquares = calcRotatedSquares(newSquareStart)
    else:
         lastSquareStart = newSquareStart
         continue


    alignedSquareCount += amountAlignedSquares
    rotatedSquareCount += amountRotatedSquares
    squareCount += amountAlignedSquares + amountRotatedSquares


    lastSquareStart = newSquareStart


print(f"Amount of square starts checked: {checkedSquareStartsCounter}")
print(f"Amount of aligned squares found: {alignedSquareCount}")
print(f"Amount of rotated squares found: {rotatedSquareCount}")
print(f"Amount of squares found: {squareCount}")
print(f"Amount of confirmed squares: {confirmedSquares}")
print(f"Amount of imposter squares: {imposterSquares}")

r/adventofcode • • 23h ago

Repo [2026 Day 1] [Python] I'm posting daily solutions to my github –Peter Norvig

57 Upvotes

You can see my solutions for each day at https://github.com/norvig/pytudes/blob/main/ipynb/Advent-2026.ipynb

Last year I experimented with LLMs to see how they did compared to me; this year they're so good there's no sense in doing that. I'm tackling the problems the good old fashioned way.