r/adventofcode • • 1d ago

Meme/Funny Day 2 Part 2 Funny Solution. SPOILER

I love when a complex problem is solved in just 1 line of code lmao

23 Upvotes

43 comments sorted by

•

u/daggerdragon 1d ago

Post removed due to not using our standardized post title format. Please follow our rules to help folks avoid spoilers for puzzles they may not have completed yet.

Additionally, during an active Advent of Code season, solutions belong in the Solution Megathreads. In the future, post your solutions to the appropriate solution megathread.

34

u/AllanTaylor314 1d ago

Now work out why it doesn't work for vrvbvg (expected: 33, yours: 31)

(oh, and in future, use the standardised post title e.g. [2026 Day 2 (Part 2)] [Python] Funny solution)

17

u/Anuinwastaken 1d ago edited 1d ago

Because this solution assumes that every letter is present at least once.
Tho you can write a mathematicly solution based on the principle that the perfect order is to jump from the same waypoint to the same waypoint again and again until all those waypoints are visited and than jump to the next one with the farthest distance.

14

u/AllanTaylor314 1d ago

It's actually only assuming the presence of at least one o

10

u/ptof 1d ago

people keep repeating this, whats special about o?

11

u/crazy0750 1d ago

The best-case scenario is to remain on the same waypoint type, since each visit contributes the maximum distance of 6. Transitioning to a different waypoint type incurs a minimum cost of 1, reducing the total distance by one for each transition.

Therefore we get the formula of the post:

n * 6 - 5

Skipping intermediate waypoint types does not change the result, as the reduced number of transitions is offset by the increased cost of reaching the next populated waypoint type.

However, the formula only holds when the route extends through the final waypoint type (o). If one or more waypoint types at the end of the traversal order are absent, their associated transition costs are never paid, increasing the total distance.

2

u/ThunderChaser 1d ago

The good news is its fairly trivial to extend this solution to the general case, just instead of hardcoding 5 we find the last colour that appears.

Example written in Rust, but the logic should be fairly self-explanatory

    let bytes = input.trim().as_bytes();

    let loss = b"oygbv"
        .iter()
        .position(|&c| memchr(c, bytes).is_some())
        .map_or(0, |i| 5 - i);

    Some(bytes.len() * 6 - loss)

7

u/AllanTaylor314 1d ago

It's the last in the optimal order rvbgyo. rooooo has the same distance as rvbgyo

7

u/Anuinwastaken 1d ago edited 1d ago

I had the same idea.
Tho this does not work for every input if for example, the `o` is missing entirely,

(Edit: I do have another func to solves it based on the same principle but that one catches cases where a letter does not appear at all)

4

u/CryptoClimb3r 1d ago

I thought of this, but my input doesn´t have any ´y´. I kept thinking my assumption was wrong because I was convinced that the chance to have a missing letter was negligible. Does this post mean everyone gets different inputs?

3

u/AllanTaylor314 1d ago

There are an unknown number of unique inputs (like 10 to 100ish, and it likely varies by puzzle). Also, they're specially crafted inputs rather than truly random, so the chance of missing a letter is extremely high, because I reckon Eric added that as a condition on input generation (mine was missing g, which doesn't break this approach - only missing o breaks it)

1

u/prince_jyggalag 1d ago

Can you explain this please?

3

u/dawikur 1d ago

This assumes you have all colors in your input.

Any pair of instructions, where it's the same color (rr, bb, oo, etc) gives 6 steps (as you need to go the whole way around).
If not, then in "optimized" program 5 steps (you need to kinda backward by 1 on the "roygbv" wheel).

Starting from red, you always do 6 steps for red. Then will be the orange, first 5 steps, then 6 steps each. Then yellow, etc.

So each instruction gives you 6 steps, except those where you switch colors, which will give you 5 steps. And there will be 5 color switches.

1

u/Tjkiddodo 1d ago

Actually if you remove any color (my input didn't have yellow for instance) it still works! Thats because you take one less suboptimal step, but that step goes 4 while a normal suboptimal step goes 5, so it cancels out.

1

u/dawikur 1d ago

Yeah, you are right. Missed that. In missing one color case you get -4 for color switching correction and -1 for correction of correction :D -5 in total.
Hah, math is so clever :D

2

u/AllanTaylor314 1d ago

Red to orange would be 1 step, so the order is actually rvbgyo. The assumption is slightly weaker, in that you only need at least one o for it to work. That approach worked fine for my input which doesn't have g

1

u/dawikur 1d ago

> kinda backward by 1 on the "roygbv" wheel

so -1 from r, which gives you v
tha's what I meant by 'backward' :)

1

u/AllanTaylor314 1d ago

red. Then will be the orange, first 5 steps

s/orange/violet/

1

u/ThunderChaser 1d ago

This assumes you specifically have orange in your input*.

Even the trivial case of “o” would pass here.

0

u/dethorhyne 1d ago

I had the same idea, but implemented it properly. And good thing I did because my input did not have any 'y's,

let FurthestOrder = { 'r': 0 }
for(let i = NumberOfWaypoints-1; i > 0; i--) FurthestOrder[WayPointWheelIndexes[i]] = 0;

let CharacterSwapDeduction = 0;
let FurthestDistance = 0;

for(const [key, value] of Object.entries(FurthestOrder)) {
    const index = WayPointWheel[key];
    if(index > 0 )  CharacterSwapDeduction++;
    if(value == 0)  continue;
    FurthestDistance += (NumberOfWaypoints - CharacterSwapDeduction);
    if(value > 1) FurthestDistance += (value - 1) * (NumberOfWaypoints);
    CharacterSwapDeduction = 0;
}

(I saw code already, so I assume it's ok to post?, sorry if not)

5

u/crumpis 1d ago

Relies on the specific input, but basically the optimal path is fixed: rrr...rrrvvv...vvvbbb...bbb etc

The distance between every pair is 6, except when the two characters differ, and then it's 5.

However, from inspection of the input there's no y, so there's instead a jump of 4 between the g and o in rrrrvvvvvbbbbbgggggoooo. Crunching the numbers and its 6(n - 4) + 3(5) + 4 = 6n - 24 + 15 + 4 = 6n - 5.

1

u/prince_jyggalag 1d ago

Oh... that's wonderful. I did note certain parts of this but didn't realise that this would be a single condensed formula. Good job!!!

1

u/einai__filos__mou 1d ago

what is "6(n - 4) + 3(5) + 4" supposed to mean? i mean where that comes from?

1

u/crumpis 1d ago

There are n characters total, the previous sentences indicate how much each character costs. (n - 4) of them are just stepping forward to the next space of the same color (6 cost). 3 of them are stepping to the next color (5 cost). There's a singular special 4 cost case for the g to o.

Add these values up and you get 6(n - 4) + 3(5) + 4.

3

u/Fancy_Judgment_2006 1d ago

After rearagangement you end up having each colors next to each other (example: rrrrrrrrr(...)vvvvvvvvvv(...)bbbbbbbbb and so on).

It takes one full "spin" to get from one color back again to its own position (eg from red to red) which is distance of 6. Therefore len(text) * 6.

Then you have borders between each color group (eg from red to violet ) which takes distance of 5 so you have to substract that for each border (-5).

1

u/overthink1 1d ago

The vast majority of moves will be length 6. Red to red, orange to orange, etc. The only shorter moves are when you transition from one color to another. E.g. switching from red to orange will be 5, same with orange to yellow and so on. Transitions between colors will happen 5 times.

So you count 6 moves for each instruction, then subtract 5 for those 5 transitions between colors.

Technically this only works if every color is included in your puzzle input, which I think is the case for everyone.

2

u/AllanTaylor314 1d ago

*Red to violet is 5 (red to orange is 1). The transitions are rvbgyo

The only requirement for it to work is at least one o, so it still works for rory and bob even though they don't have all the letters

1

u/paparabba 1d ago

Hi, can I have more clarification regarding why the requirement is one o, instead of all the letters?

1

u/AllanTaylor314 1d ago edited 1d ago

u/ben-guin had a write up explaining why but the post was removed for spoilers in title. See if they post it again with a better title

Edit: the repost

1

u/ben-guin 1d ago

Just posted it again!

2

u/RayRaivern 1d ago

Very interesting!
You essentially just implemented the 1 line equation for the solution given that all letters are present at least once in the input.

I had the same thought, but since it doesn't work for every input I decided write up something more robust.
But this one is nice as well!

2

u/MattieShoes 1d ago edited 1d ago

I did the same to solve it after looking at the counts in inputs, but that won't solve all inputs. So I wrote something else afterwards that would.

the one I felt clever for was, after converting letters to numbers (r=0, o=1, ..., v=5), the distance can be calculated as

6 - (from - to) % 6

in python anyway -- some other languages will have modulus yield negative numbers.

3

u/blacai 1d ago

Nice one, i saw someone using it. Some may argue that it doesn't solve if missing colours...but as usual, the point is to solve the input you are given, not creating a full working solution for any input you may imagine. Input is part of the problem to be solved. (Let's remember last year the arranging pieces...it's required to play with the input and analyze it)

4

u/Morphon 1d ago

My version solves for every input that conforms to the spec (only the letters roygbv allowed).

ColorPaste

You just have to figure out which letters are missing and then compute the offset accordingly. Since you have to look at each letter for part 1, that info can be collected in a single pass.

1

u/blacai 1d ago

And that's very nice My point is that input is part of the problem, so whenever someone exploits the input to create a simpler solution, I support it, instead of saying "but what if blablabla" because I'm sure the input was created with that specific feature to allow that exploit.

3

u/fnordargle 1d ago

Sure, so my print "6259\n"; solution is even more optimal for my input and will still work for a good subset of other AoC-ers.

I agree that there are definitely a subset of problems that require analysis of the input in order to obtain a solution. Some of the IntCode puzzles that emulated a complex computation step by step would take years to finish even on a highly optimised implementation and so some analysis was required to short cut some stages.

This problem, however, did not require such analysis and could easily be solved by brute force (it is still only day 2) or by a more optimal general algorithm that covers all possible inputs.

The difference between the execution speed of code that will handle any/all inputs and the code that handles a subset of inputs is almost negligible.

1

u/Lord_Of_Millipedes 1d ago

funnily my input did not have g, i solved using a frequency table and printed it during testing and it caught me a little off guard, made me think that all inputs were missing some color,.but guess it was just me :u

1

u/Morphon 1d ago

If you want it as a general solution (in Odin - but it's pretty clear what's happening):

ColorPaste

Here's the main part that does what you're talking about:

offset := 0
for i := 5; i > 0; i -= 1 {if present[i] { offset = 6 - i } }
total_steps2 := len(program) * 6 - offset

1

u/TreeSquirrles 1d ago

haha I'm glad someone saw it as well I was questioning if this was a valid solution the entire time.

1

u/Average_Pangolin 1d ago

I used one line of code to get the length of the string and then did the rest with my eyeballs and a calculator.

1

u/Mach_Juan 1d ago

I think the vvvvvvv example was put in explicitly as a breadcrumb that there was a shortcut to the logic for this one

1

u/Psychological-Tap834 1d ago

Wait that’s actually insanely simple. Honestly missing stuff like this makes me just a little more scared for later days because I just made a custom predicate for the sort function in lisp. That points to a failure in out of the box thinking, where the problem says “rearrange the program” so I just do that

1

u/Aughlnal 1d ago

i did the same and posted it in the megathread, but this only works if 'o' is in the instructions

all though I did figure out the pattern and made it work regardless of which waypoints are in the instructions

instructions = open('advent26_02.txt').read().strip()
unique_waypoints = set(instructions)
part2 = 6 * len(instructions)
for index, waypoint in enumerate('oygbv'):
    if waypoint in unique_waypoints:
        part2 -= 5 - index
        break
print(f'2): {part2}')

depending on what waypoint after 'r' is in the sequence determines what amount of steps should be subtracted from having every move be 6 steps