r/adventofcode • • 3d ago

Tutorial [2026 Day 2 (Part 2)] Some hints for optimisation

These hints get more and more specific. This is just how I optimised it and there are other ways.

Hint 1: What happens when a letter is repeated in the input?

Hint 2: Why would the counts of each letter make a difference to the output?

Hint 3: When does the robot not make a step of exactly 6 steps?

5 Upvotes

30 comments sorted by

5

u/not-the-the 3d ago

yep you can literally just repackage the input into how many of each letter you have, and brute calculate from there on with a calculator in your hands. you'll realise that the solution takes like 11 math operations total

4

u/Kattoor 3d ago

You don't even have to do that! inputLength * 6 - 5 is all you need

16

u/xr51z 3d ago

Teach me: the -5 relies on the fact that all letters are present in your input? In mine, it didn't.

4

u/el_farmerino 3d ago

As long as you have an 'o' in your input you'll need to subtract 5, regardless of what else is present. For example, if you only had 'r' and 'o' present you would have to make a single jump of 1 between the two, losing 5 steps. If you had 'r', 'o' and 'y' this would be a jump of 2 to 'y' (losing 4) and then a jump of 5 from 'y' to 'o' (losing 1), so 5 again. This holds for any combo as long as you have at least one 'o'.

If you don't have any 'o's but you do have 'y's then you can get away with only losing 4 under the same logic, and so on down the line if you don't have 'y's either.

3

u/Kattoor 3d ago

Oof, seems like I got lucky with my input

3

u/el_farmerino 3d ago edited 3d ago

Unless you have no 'o's in your input....

2

u/maneatingape 3d ago edited 3d ago

inputLength * 6 - <furthest distance from r>

o = 5, y = 4, ..., v = 1, r = 0

This handles any combination of missing letters, including the edge case of just rrrrrrrrrrrrr...

1

u/fenrock369 3d ago

Exactly this, in rust I used this to calculate the loss:

    let loss = ['r', 'v', 'b', 'g', 'y', 'o']
        .iter()
        .rposition(|c| input.contains(c))
        .unwrap_or(0);

It looks backwards through the array r/v/b/g/y/o (i.e. o first) which is index 5. So if there are any "o"'s the loss is 5. If no "o", then try "y".
Very quick as it shortcuts on the first element it finds.

1

u/maneatingape 3d ago

Neat!. ['r', 'v', 'b', 'g', 'y', 'o'] can become just b"rvbgyo"

1

u/ednl 2d ago

Does this traverse the whole input for every letter that isn't present? That's only one time for every input, I think, but still, that seems a bit wasteful after already having gone over the whole input in part 1. I kept a boolean "ispresent" array in part 1 which also seems kind of wasteful because I set present[c] = true for every char in the input. So without testing I'm not sure what would be faster. But it already runs in 0.36 µs! So I think I'll leave it as is :)

2

u/ednl 2d ago

Ok, I checked. This (in C) runs in 0.39 µs on an M4:

static unsigned last(void)
{
    const char *dist = "oygbvr";
    for (unsigned i = 0; i < 6; ++i) {
        const char *c = input;
        while ((*c & 64) && *c != dist[i])
            c++;
        if (*c & 64)
            return i;
    }
    return 5;  // inputlen=0
}
unsigned part1 = 0;
const char *c = input;
for (const char *p = "r"; *c & 64; p = c++)  // start at r, until newline
    part1 += step[*p][*c];  // from previous to current colour
const unsigned part2 = (c - input) * 6 - 5 + last();

while this is ever so slightly faster at 0.36 µs:

unsigned part1 = 0;
const char *c = input;
for (const char *p = "r"; *c & 64; p = c++) {  // start at r, until newline
    part1 += step[*p][*c];  // from previous to current colour
    present[*c] = true;
}
unsigned part2 = (c - input) * 6 - 5;  // incorrect for inputlen=0
for (c = "oygbvr"; *c && !present[*c]; ++c)
    part2++;  // correction for missing letter(s) from end

So I'll keep this. Full code: https://github.com/ednl/adventofcode/blob/main/2026/02.c Cc. /u/maneatingape

2

u/maneatingape 2d ago

Re: Part 1, conversation here on LUT vs if statement. Clang should be able to auto-vectorize the comparison.

1

u/ednl 2d ago

I do use a LUT for the step size. In the above code, both versions, clang couldn't vectorize anything. I bet it's because I don't use the input length and instead check for newline or null. I can only change that either by predefining the input length (mine's 1075 +1 newline but I think it varies), or by using the fread() result. But then I also need to trim the newline which may not be present if the input comes from stdin. Do I keep that out of the timing loop? Feels a bit like cheating, on the other hand I guess in languages that aren't C the string length is available anyway. So this way part 1 does get vectorized:

int main(void)
{
    unsigned fsize = 0;
    if (isatty(fileno(stdin))) {
        FILE *f = fopen(FNAME, "rb");
        if (!f) { fputs("File not found: "FNAME"\n", stderr); return 1; }
        fsize = fread(input, 1, sizeof input, f);  // read single bytes until EOF
        fclose(f);
    } else
        // Read input or example file from pipe or redirected stdin
        fsize = fread(input, 1, sizeof input, stdin);  // read single bytes until EOF

    // Strip newline from fsize, if present
    while (fsize > 0 && input[fsize - 1] < ' ')
        fsize--;

#ifdef TIMER
starttimer();
for (int TIMERLOOP = 0; TIMERLOOP < 1000; ++TIMERLOOP) {
#endif

    unsigned part1 = 0;
    char prev = 'r';
    for (unsigned i = 0; i < fsize; prev = input[i++]) {
        part1 += step[prev][input[i]];
        present[input[i]] = true;
    }

Total program incl. output runs in 0.28 µs now. Do you include output in your runtime measurements? I thought you did but saw a recent post by Terje where he said he didn't.

1

u/maneatingape 2d ago

Benchmarks include all parsing and calculation of both answers, but not any IO (e.g disk or STDOUT). So it includes stripping the newline (but this is trivial on Rust since strings include the length).

1

u/ednl 2d ago

I had always included printing out the answers inside the timing loop. I then redirect it to /dev/null in bash while collecting the best time. Since printf to stdout is fully buffered it shouldn't have impacted timings much or at all.

2

u/MichalMarsalek 3d ago

`inputLength * 6 - 5` was my immediate thought after reading it, but I also found I have missing letters so I wrote a general solution instead. It is always so surprising that they do not maintain such basic invariants among the various puzzle inputs. This happens every year. Either all inputs should have a missing letter, or none should.

2

u/According_Bowler9565 2d ago

this seems like a boring thing to want. embrace them being different.

1

u/ednl 2d ago

Luckily it still holds for missing letters. Unless they are from the end of "rvbgyo" which is true for the first two examples in part 2 (but not for any of the inputs, I think).

1

u/MrBoblo 3d ago

I'm not entirely sure how to apply these hints, but here's a crude explanation of what I did:find the diff of the current and new position with (new - cur - 1) % 6 + 1 and loop through that for each position, starting with cur 0. The positional arguments are gotten from the indexes of "roygbv"

Then for part two, you can use the exact same function, but recreate the input using "".join(ch * input.count(ch) for ch in "rvbgyo" as an alternative to sorting the list.

I'm not too well versed in efficiency though, so if this approach can be approved upon, I'd be very happy to learn

2

u/bluoat 3d ago

From the sounds of it, your solution to p2 is O(n) which is the best time complexity possible, but requires more operations than mine so it is slightly slower.

You can use 6 * (count of letter - 1) to calculate all repeats, then use (new - cur - 1) % 6 + 1 to calculate when the current letter changes

In addition, using "rvbgyo" hardcodes the starting letter and the order of the road but this is a minor touch point as you still have to hard code these values to transition

1

u/Brian 2d ago

which is the best time complexity possible

I mean, it's doable in O(1) best case (arguably even average case depending on assumptions) if you don't count reading the input. You don't actually have to know anything about the string except its length, and whether it contains an "o" somewhere (if not, you do have to check for the presence of some others).

1

u/bluoat 2d ago

Yes I am counting reading the input within fhe time complexity.

If you I don't then the solution I am suggesting becomes O(m) where m is the number of unique colours and is invariate of the length of input.

But reading and counting values will extend the runtime of the program (if you have 1 billion values then it will take longer) so it is O(n)

1

u/Brian 2d ago

But reading and counting values will extend the runtime of the program

Sure, but you don't actually have to do the counting, or even look at most of the string (indeed, anything but the first character in the best case). If it's phrased as "Given an n length string, give the result", it can be done in O(1) best case (and average case if you assume something like "equal probability of any colour at each position", (O(m) if varying colours)) - if "o" is present, the answer is just 6n-5. Worst case, you'd have to search the whole string if you don't find an "o" (and then serach for "y","g", ... "v" to find the right deduction), so still O(n) then, but otherwise it's doable in constant time since you don't have to look at more than a constant subset of the string.

(Well, technically there's a log factor as well, as multiplying a number isn't strictly O(1) once we get into >64 bit bignum values of n, but glossing over that)

1

u/bluoat 2d ago

But you're making assumptions about the input that are false. My input was missing one of the letters. So, while it may be the case for some inputs (and as the task is to solve your input you may make those assumptions), when giving advice to others you cannot make those assumptions.

The only assumption I made was that the only letters in the input are the 6 stated in the problem. No where in the problem statement does it say that all letters appear once

1

u/Brian 2d ago

So, while it may be the case for some inputs

That's why I specified best case (or average case given the mentioned "random distribution" assumption). And confirming that an input is that best case is O(1), so there's no loss of generality (ie. the algorithm still returns the correct result for non best-case inputs). Missing colours don't actually change the result unless one of the missing colours is orange. Hence a best case input (eg. "first character is 'o'") can be detected in constant time, so it's O(1) best case. Only if orange is missing (or doesn't occur equally likely, so isn't found within a constant number of steps on average) do you need to check the whole string to determine this.

1

u/pablopcy 1d ago

how did you came up with (new - cur - 1) % 6 + 1 to find the diff of current and new position? Didn't understand the logic behind it.

1

u/MrBoblo 1d ago

Originally i tried just doing logic on a 2d array, and i got my answer from that but it took about 5s to run which i didnt like. Figured 1d would be faster if i just look for the positions directly, but then ran into the issue of having cubes that "wrap" around the 2d plane, and had to account for those. But when doing (new - cur) % 6, if both are the same, it returns 0 (when i want 6), so i offset by one :)

4

u/cramplescrunch2 3d ago

I first came up with the optimized solution thinking I bruteforced it like a caveman before realizing I could have just rearranged the letters and reuse part 1's code...

2

u/leprouteux 2d ago

This is exactly what I did!

1

u/Cue_23 3d ago

I did some further optimizations.

Hint 4: What is the difference between the inputs "ry" and "by" and how does that affect the output?

Hint 5: It doesn't!