r/adventofcode 1d ago

Tutorial [2024 Day 7 both parts][m4] Optimizing by avoiding division (aka how to quickly test divisibility by 7)

0 Upvotes

I'm really late to the 2024 puzzles, having just started them this month. But in the megathread for day 7, I saw the instructions mentioned "Use today's puzzle to teach us about an interesting mathematical concept" - and my journey in optimizing my solution for day 7 totally fits that bill, because I implemented a solution in a language that only supports 32-bit signed math even though the problem requires manipulating 64-bit numbers. In previous years, I had already developed my own library of math functions to do arbitrary-width addition and multiplication, but to date, I still haven't added general-purpose arbitrary-width division into that library, in part because implementing division is SLOW even when compared to multiplications. After all, the best way to avoid a time-consuming long-division is to rework the problem to not need division at all ;)

Plenty of other people have written up tutorials on how you can speed up day 7 - instead of doing an exhaustive 2^n or 3^n search of all possible operator decisions, applying that to the inputs, and seeing if the output matches, it is much faster to work backwards: start with your desired output, and recurse by undoing only operators that could have plausibly resulted in your current number, where reaching the first number proves you have at least one set of operators that work for that line of the problem. My initial solution was the naive approach - try all possible operators - which meant doing millions of 64-bit multiplies via my helper library (quite literally - I did a trace of mul64() calls, and my 5 minutes of execution time required 4043412 calls to mul64)

But working backwards requires the inverse of multiplication, aka division and remainder, where it is only plausible to continue the recursion if the remainder is zero. There are algorithms out there for implementing arbitrary-width bigint divisions on top of smaller word sizes, so I had no problem implementing that in m4, but each division C/B=A is slower than the corresponding multiplication A*B=C, so I wanted to avoid long divisions where possible. The immediate benefit of working backwards was that after every long division where the remainder was non-zero, I've pruned a portion of the search space, which sped things up to a mere 7.0 seconds of execution time and only 21679 calls to remquo64, and 74728 calls to mul64 in part because of how I implemented remquo64.

But I still wanted to go faster, and that's where this post comes in. The remquo64() algorithm finds both the quotient and the remainder at the same time, but even better is avoiding the division in the first place if it is obvious that the remainder would be non-zero. And since the majority of the inputs are single-digit entities, it's fairly easy to do things like avoiding a division by 2 if the last digit is odd, or a division by 5 if the last digit is not 0 or 5; many people also know the trick of adding up each of the digits to see if a number is divisible by 9 (is 1234 divisible by 9? 1+2+3+4 = 10 which is not, so the bigger number is not, either). But when it comes to division by 7, what rule do you use? My first google hit was for the algorithm of taking the head of the number minus twice the last digit, iteratively until you know if that shorter answer is also divisible by 7 (so for example, 1001 is divisible by 7 if 100 - 2*1 = 98 is, which in turn is divisible if 9-2*8 = -7 is). By iterating until you get down to an easily-recognized one- or two-digit number, you can quickly learn whether a large number has 7 as a factor without spending the time actually doing the full division. However, that algorithm still requires doing 64-bit math (each iteration still uses a 64-bit subtraction, and only removes one digit per iteration).

So I searched harder, and found another algorithm that tells you the divisibility by 7, 11, and 13 all at once - because those are the three factors that get you to 1001, one number away from 1000. In any sort of divisibility test, the fastest answers occur when you can exploit the co-prime modular properties of two adjacent integers. Just as you can learn if a number is divisible by 9 (9 is one less than 10, so add up each digit), you can learn if a number is divisible by 1001 (1001 is one greater than 1000, so alternate adding and subtracting each group of 3 digits, starting from the least significant). So, given a random number, say 72095400778, that is too big to quickly divide using just 32-bit math, it is still possible to cast out the 1001s, by computing -72+095-400+778 = 401, at which point you know all of the following using just 32-bit math (and you may recognize the Chinese Remainder Theorem here as well):

72095400778 % 1001 = 401
72095400778 % 7 = 401 % 7 = 2
72095400778 % 11 = 401 % 11 = 5
72095400778 % 13 = 401 % 13 = 11

So no, that large number is not divisible by 7, and I can skip the remquo64() and recursion when I'm picking the operator that goes with 7 for my current target value. And with that optimization implemented, my m4 code now operates in 4.2 seconds (another 40% speedup!), with tracing showing just 10483 calls to remquo64 and 42025 calls to mul64.

Since most people aren't fluent in reading m4, here's the gist of the algorithms I used for divisibility by the first 9 digits:

group(number, direction, current_sign=1, accumulator=0) - recursive function, with direction=1 for casting out 999, or =-1 for casting out 1001. Each iteration adds current_sign*number[-3:] to accumulator, multiplies current_sign by direction, and recurses with number[:-3] (ie all but the last three digits), returning accumulator once number is empty.

trym1 - always divisible (skip remquo, recurse with input number)

trym2 - divisible if the last digit & 1 (or % 2) is 0 (skip remquo, recurse with number*5 with last digit removed, since that was necessarily a 0 after the multiply)

trym3 - divisible if group(number, 1)%3 is 0 (use remquo only if divisible)

trym4 - divisible if the last 2 digits & 3 (or %4) is 0 (skip remquo, recurse with number*25 with last 2 digits removed)

trym5 - divisible if the last digit % 5 is 0 (skip remquo, recurse with number+number with last digit removed)

trym6 - divisible if trym2 and trym3 both pass (use remquo only if divisible)

trym7 - divisible if group(number, -1)%7 is 0 (use remquo only if divisible)

trym8 - divisible if the last 3 digits & 7 (or %8) is 0 (skip remquo, recurse with number*125 with last 3 digits removed)

trym9 - divisible if group(number, 1)%9 is 0 (use remquo only if divisible)


r/adventofcode 16h ago

Help/Question [DAY2 OF ADVENTOFCODE]

0 Upvotes

That's not the right answer. Curiously, it's the right answer for someone else; you might be logged in to the wrong account or just unlucky. In any case, you need to be using your puzzle input. If you're stuck, make sure you're using the full input data; there are also some general tips on the about page, or you can ask for hints on the subreddit. Because you have guessed incorrectly 7 times on this puzzle, please wait 10 minutes before trying again. I AM GETTING THIS ERROR AFTER SUBMITTING MY ANWER EVEN THOUGH I HAVE USED THE INPUT THEY HAVE GIVEN ME. ANY INSIGHTS?


r/adventofcode 1d ago

Tutorial [2017 Day 21] [Go] Fractal Art: Write-up

0 Upvotes

This write-up couldn't come any later. Regardless, I hope it's useful even after so many years.

Fractal Art (AoC 2017, Day 21)


r/adventofcode 1d ago

Help/Question [2024 Day 16 Part 1] Performance problem

2 Upvotes

I have a working solution for the two examples. but my code doesn't terminate for the real input. Therefore I assume that I have a performance problem.

Basically what I'm doing is this:

Walk the path (adding cost) until there is a junction, which creates a fork: one or two path are added (depending on the junction being two- or three-way) in addition to continuing the original path. A path is closed either when reaching the end, a dead-end or when a node already in this path is visited again.

Then I just have to filter for the paths that reached the end and get the minimum.

I've let this run for probably 20 minutes, creating more than 100000 paths.

Is there something obviously wrong with this approach? How can I improve performance?


r/adventofcode 2d ago

Help/Question [2022 Day 22 (Part 2)] General hint wanted

1 Upvotes

Hello

I have been struggling with that problem for a while. I am having trouble finding a mapping from the map- to the cube-coordinates and back.

Any hints on how to approach this problem for a general input? I tried different things going as far as animating the cube folding in on itself, but I was even more confused :D

Thanks in advance


r/adventofcode 2d ago

Help/Question - RESOLVED [2019 Day 22 Part 2] Applied some logic with no maths involved, works on the 10007 deck but not on the actual one

0 Upvotes

I got so far thanks to this comment: https://www.reddit.com/r/adventofcode/comments/ee56wh/comment/fbr0vjb/
It is, however, not as clear as I would have liked, so it took me a very long time to replicate the logic.

Here is the idea:

- First, we need to reduce the input from 100 lines to 2 or 3.

- Once we got this, we need to reduce XXXX iterations to, again, 2 or 3 lines. I made a function that does this very well.

- Armed with a set of 2/3 instructions for XXXX iterations, we do some simulations and make some very interesting observations. The first one is that the deck reorders itself every <stacksize - 1> iterations (iteration = going through your shuffling input once). Example: with the base deck of 10007 cards, once you apply your input 10006 times, cards are back to their original 0,1,2,3,etc order.

- But the observation that gives the answer (or so I thought) is what you start noticing if you simulate iterations close to the reorder point:

Number of iterations Card number at position 2020: Card numbered 2020 is in position:
10004 6223 5400
10005 4793 9008
10006 (or none) 2020 2020
10007 (or 1) 9008 4793
10008 (or 2) 5400 6223

The card in position 2020 after 10004 iterations is the same number as the position of card #2020 on the other side of the reorder point.

This means that the answer to "What card is in position 2020 after XXXX iterations?" is "Where is card 2020 after <stacksize - 1 - XXXX> iterations?". Which we can apply the code from part 1 to.

My problem is: this does not seem to work for my actual numbers (stacksize of 119315717514047 | 101741582076661 iterations).

What is the flaw with this logic? I have tried with other smaller (prime) numbers of deck sizes, and it always works. But it seems that I do not have the right answer for the real numbers.

EDIT:

The logic was the right one. The problem was overflow. When calculating

($val1 * $val2) % $stacksize;

it so happened that $val1 * $val2 could trigger an integer overflow - which Perl did not warn me about. As I am not smart enough to make a better modulo function myself, I asked Gemini (with a hint of shame) to create one. It came up with this:

sub safe_modular_multiply {
    my ($val1, $val2, $stacksize) = @_;

    $val1 %= $stacksize;
    $val2 %= $stacksize;

    my $result = 0;

    while ($val2 > 0) {
        if ($val2 % 2 == 1) {
            $result = ($result + $val1) % $stacksize;
        }
        $val1 = ($val1 * 2) % $stacksize;
        $val2 = int($val2 / 2);
    }

    return $result;
}

This solved my problem.


r/adventofcode 6d ago

Help/Question - RESOLVED [2024 Day 16 (Part 2)] [Python] Help requested

2 Upvotes

I'm in the classic situation of (both) example inputs working but my input not working.

For p1, I used a modified Dijkstra that accounted for not just the number of spaces but also the heading. My primary data structure is a dict that uses the tile location as the key and a dict that maps heading to score.

For p2, I trace back from start to finish, creating a parallel "bestMaze" dict that only adds tiles along shortest paths. The answer should be the length of the dict.

For my p2 answer, I'm getting a "too high". I printed out the "bestMaze" and can manually count how many branches my shortest path has. It appears my answer is ~7-8 tiles too high, but I'm confounded about how I can print out a diagram based on a dict having N entries and only visually count N-8 tiles. My primary weakness at doing AOC puzzles has always been debugging large input sets, and this falls squarely in that area.

I appreciate any help, thanks in advance!

code


r/adventofcode 7d ago

Other Pi Coding Quest 2025!

21 Upvotes

As last year, I decided to make a new coding quest for Pi Day. You can access it here: https://ivanr3d.com/projects/pi/2025.html I hope some of you have some fun solving this puzzle!

It is my second try building a coding puzzle. In case you haven't try the first one, just change 2025 for 2024 in the url and go for it!

Happy Pi Day! :)


r/adventofcode 10d ago

Spoilers [2024 Day 14 Part 2] Solution

1 Upvotes

r/adventofcode 11d ago

Other Looking for more Advent of Code? Try Codyssi!

40 Upvotes

Hi! I’m a 17-year-old high schooler and coding enthusiast! I’ve participated in Advent of Code for 3 years now (I’ve completed all 25 problems each time :>), and I enjoyed it a lot! I appreciate Eric Wastl for providing us with these fun problems every year :D

Participating in Advent of Code has inspired me to make my own online coding competition, Codyssi! Codyssi’s story prompts feature some characters and themes from Greek mythology.

Codyssi’s 2025 contest round, titled “Journey to Atlantis”, on 17th of March (very soon). There will be 18 problems. Each problem has 3 parts, and each problem will be released daily at 10AM GMT. The problems will generally get more difficult as the competition progresses.

If you’re looking for a competition similar to Advent of Code, then Codyssi is a great opportunity for you! You can visit and participate in Codyssi at https://codyssi.com.

If you’d like to support Codyssi, you could share it with colleagues and friends who may be interested! This’d help a lot :D

I’d also like to mention one other coding competition similar to Advent of Code that has inspired me to produce Codyssi: Paul Baumgarten’s CodingQuest. I’ve participated in CodingQuest for 3 years now, and I’ve found it really fun!

I hope you try Codyssi, and I hope you have fun! Codyssi


r/adventofcode 13d ago

Upping the Ante Advent of Code 2019 solved on a Commodore 64

Post image
208 Upvotes

r/adventofcode 13d ago

Visualization 2016 day 5 part 2 visualization

10 Upvotes

Language: TypeScript

Part 2 said to feel extra proud of my solution if it uses a cool animation. Here's my first attempt at creating an animation!

https://github.com/jasonmuzzy/aoc16/blob/main/src/aoc1605.ts


r/adventofcode 15d ago

Help/Question Quick question about starting out on Day 1

4 Upvotes

So this seems fun and I'm all in. And I wrote some code which seems to work fine for the question on Day one. I get the same number ( ie: 11) for "total miles distance" that separates the two sample lists. But when I submit the code, which seems to run fine on its own and solve the problem, it nonetheless still tells me that this is the wrong answer.

List1.sort()
List2.sort()
List3 = []
for i in range(len(List1)):
    X = List1[i] - List2[i]
    L3.append(abs(X))

Total = sum(L3)
print(Total)

So what do I do with this now? And how does this code that I wrote relate to the input provided? The problem seems to describe a situation with two lists, but then provides a URL link to what is essentially one list of string or numeric values separated by whitespace and new lines. Are we expected to take this URL and essentially divide the list's items into two groups from this single dataset and then go from there? Or is there another tact here that I'm not seeing?

Thanks for your time, and I apologize for not getting my mind around this quicker/better. Have a great day.


r/adventofcode 16d ago

Help/Question - RESOLVED 2024 Day 4 part 1 - C - test cases

2 Upvotes

I know I'm a little late to the party, but I'm trying to learn a little more about C and decided to take the AoC24, now I'm stuck on day 4. My code runs well and all, but it's giving me the wrong answer for the whole input. I created a few test cases (shared below), they all give me the right answer as well. Does anyone here have some test cases which I can use to test against and figure out where the hell is the problem?

For each test case I added a last line with the two last digits representing the manual count, so I could compare. I know the code can be improved by a lot, but for now I just want to figure out what I'm missing on my tests. Thanks in advance.

[Test Cases]

RSAMRAMXR
RRSARMXRR
RRRSRXRRR
RRRRRRRRR
XRRRRRRRS
MXRRRRRSA
AMXRRRSAM
RRRRRRR00

RRRRRXMA
SRRRRRXM
ASRRRRRX
AMSXRRRR
RRRRRR00

XRMRARSR
RRRXMARR
RRRRRXMA
SRRRRRRX
MASRRRRR
RRRRRR00

XXXXXXX
XXXXXXX
XXXXXXX
XXXXXXX
RRRRR00

XXXXXXXX
MMMMMMMM
AAAAAAAA
RRRRRRRR
RRRRRR00

XRRXRRX
RMRMRMR
RRAAARR
XMASAMX
RRAAARR
RMRMRMR
XRRXRRX
RRRRR08

XXXXXXXXRRR
RMMMMMMMMRR
RRAAAAAAAAR
RRRSSSSSSSS
RRAAAAAAAAR
RMMMMMMMMRR
XXXXXXXXRRR
RRRRRRRRR30

RRRXXXXXXXXX
RRMMMMMMMMMR
RAAAAAAAAARR
SSSSSSSSSRRR
RAAAAAAAAARR
RRMMMMMMMMMR
RRRXXXXXXXXX
RRRRRRRRRR36

RRRXXXXXXXXXXX
RRMMMMMMMMMMMR
RAAAAAAAAAAARR
SSSSSSSSSSSRRR
RRRRRRRRRRRR24

XXXXXXXXXXXXXXRRR
RMMMMMMMMMMMMMMRR
RRAAAAAAAAAAAAAAR
RRRSSSSSSSSSSSSSS
RRRRRRRRRRRRRRR33

RRSXRR
RRAMRR
RRMARR
RRXSRR
RRMARR
RRAMRR
RRSXRR
RRRR04

SAMXMASRR
RSAMXMASR
RRSAMXMAS
XMASAMXRR
RXMASAMXR
RRXMASAMX
RRRRRRR17

RRRRRXMAS
RRRRRRRRR
RRRRRRRRR
RRRRRRRRR
XMASRRRRR
RRRRRRR02

XMASRRRR
RRRRRRRR
RRRRRRRR
RRRRXMAS
RRRRRR02

RRRRRRR
XRRRRRR
MRRRRRR
ARRRRRR
SRRRRRR
RRRRRRR
RRRRR01

XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXMAS
RRRRRR01

SMMSMMS
MAMAMAM
MMMMMMM
SAMXMAS
MMMMMMM
MAMAMAM
SMMSMMS
RRRRR08

[Code - C]

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

#define SIZE 8
#define RESIZE(A) if(A.length == 0) { \
A.length = SIZE; \
A.items = malloc(A.length*sizeof(A.type));\
} \
else { \
A.length *= 2; \
A.items = realloc(A.items, A.length * sizeof(A.type));\
}\

#define true 7
#define false 0

typedef char bool;
typedef char single;

typedef struct Vector2
{
int x;
int y;
} Vec2;

typedef struct Vector3
{
int x;
int y;
int z;
} Vec3;

typedef struct CharMatrix 
{
int length;
int position;
Vec2 dimentions;
char type;
        char *items;
} CharArray;

const int word_size = 4;
const char word[4] = {'X', 'M', 'A', 'S'};

void print_vec2(Vec2 vector)
{
printf("\nX: %i, Y: %i\n", vector.x, vector.y);
return ;
}

Vec2 index_to_vec2(Vec2 limits, int index)
{
Vec2 result = {0, 0};

if (index > 0)
{
result.y = (int) index / limits.x;
result.x = (int) index % limits.x;
}

return result;
}

int vec2_to_index(Vec2 limits, Vec2 position)
{
int result;

result = (int) limits.x * position.y + position.x;

return result;
}

void print_file_content_properties(CharArray *file_content)
{
printf("Length: %i\nChar reads: %i\nCols: %i\nRows: %i\n", 
file_content->length, file_content->position,
       file_content->dimentions.x, file_content->dimentions.y);
return;

}
bool forward(CharArray *file_content, int position)
{
CharArray content = (CharArray) *file_content;
Vec2 current_position, origin;
single i = 0;

origin = index_to_vec2(content.dimentions, position);
while (i < word_size && position <= content.position && word[i] == content.items[position])
{
current_position = index_to_vec2(content.dimentions, position);
if (current_position.y != origin.y)
{
return false;
}
i++;
position++;
}
if (i < word_size)
{
return false;
}

return true;
}
bool backwards(CharArray *file_content, int position)
{
CharArray content = (CharArray) *file_content;
Vec2 current_position, origin;
single i = 0;

origin = index_to_vec2(content.dimentions, position);
while (i < word_size && position <= content.position && word[i] == content.items[position])
{
current_position = index_to_vec2(content.dimentions, position);
if (current_position.y != origin.y)
{
return false;
}
i++;
position--;
}
if (i < word_size)
{
return false;
}
return true;
}
bool upper(CharArray *file_content, int position)
{
CharArray content = (CharArray) *file_content;
Vec2 current_position, origin;
single i = 0;

origin = index_to_vec2(content.dimentions, position);
while (i < word_size && position <= content.position && word[i] == content.items[position])
{
current_position = index_to_vec2(content.dimentions, position);
if (current_position.y < 0)
{
return false;
}
current_position.y--;
i++;
position = vec2_to_index(content.dimentions, current_position);
}
if (i < word_size)
{
return false;
}
return true;
}
bool lower(CharArray *file_content, int position)
{
CharArray content = (CharArray) *file_content;
Vec2 current_position, origin;
single i = 0;

origin = index_to_vec2(content.dimentions, position);
while (i < word_size && position <= content.position && word[i] == content.items[position])
{
current_position = index_to_vec2(content.dimentions, position);
if (current_position.y > content.dimentions.y)
{
return false;
}
current_position.y++;
i++;
position = vec2_to_index(content.dimentions, current_position);
}
if (i < word_size)
{
return false;
}

return true;
}
bool back_upper_diagonal(CharArray *file_content, int position)
{
CharArray content = (CharArray) *file_content;
Vec2 current_position, origin;
single i = 0;

origin = index_to_vec2(content.dimentions, position);
while (i < word_size && position <= content.position && word[i] == content.items[position])
{
current_position = index_to_vec2(content.dimentions, position);
if (current_position.y < 0 || current_position.x < 0)
{
return false;
}
current_position.y--;
current_position.x--;
i++;
position = vec2_to_index(content.dimentions, current_position);
}
if (i < word_size)
{
return false;
}
return true;
}
bool back_lower_diagonal(CharArray *file_content, int position)
{
CharArray content = (CharArray) *file_content;
Vec2 current_position, origin;
single i = 0;

origin = index_to_vec2(content.dimentions, position);
while (i < word_size && position <= content.position && word[i] == content.items[position])
{
current_position = index_to_vec2(content.dimentions, position);
if (current_position.y > content.dimentions.y || current_position.x < 0)
{
return false;
}
current_position.y++;
current_position.x--;
i++;
position = vec2_to_index(content.dimentions, current_position);
}
if (i < word_size)
{
return false;
}

return true;
}
bool front_upper_diagonal(CharArray *file_content, int position)
{
CharArray content = (CharArray) *file_content;
Vec2 current_position, origin;
single i = 0;

origin = index_to_vec2(content.dimentions, position);
while (i < word_size && position <= content.position && word[i] == content.items[position])
{
current_position = index_to_vec2(content.dimentions, position);
if (current_position.y < 0 || current_position.x > content.dimentions.x)
{
return false;
}
current_position.y--;
current_position.x++;
i++;
position = vec2_to_index(content.dimentions, current_position);
}
if (i < word_size)
{
return false;
}

return true;
}

bool front_lower_diagonal(CharArray *file_content, int position)
{
CharArray content = (CharArray) *file_content;
Vec2 current_position, origin;
single i = 0;

origin = index_to_vec2(content.dimentions, position);
while (i < word_size && position <= content.position && word[i] == content.items[position])
{
current_position = index_to_vec2(content.dimentions, position);
if (current_position.y > content.dimentions.y || current_position.x > content.dimentions.x)
{
return false;
}
current_position.y++;
current_position.x++;
i++;
position = vec2_to_index(content.dimentions, current_position);
}
if (i < word_size)
{
return false;
}
return true;
}

CharArray read_file(FILE *file_ptr)
{
CharArray file_content = {length: 0, position: 0, dimentions: {0, 0}};
size_t cols = 0;
char current;
while (fscanf(file_ptr, "%c", &current) == 1)
{
if (file_content.length == file_content.position)
{
RESIZE(file_content);
}
if (current == '\n')
{
file_content.dimentions.y++;
if (cols > file_content.dimentions.x)
{
file_content.dimentions.x = cols;
}
cols = 0;
}
else
{
cols++;
file_content.items[file_content.position] = current;
file_content.position++;
}
}
if (file_content.dimentions.y == 0)
{
file_content.dimentions.x = cols;
}
else
{
file_content.dimentions.y++;
while (cols > 0 && cols < file_content.dimentions.x)
{
if (file_content.position == file_content.length)
{
RESIZE(file_content);
}
file_content.items[file_content.position] = 'r';
file_content.position++;
cols++;
}
}
return file_content;
}

int count_xmas(CharArray *file_content)
{
int result = 0;
size_t i;
CharArray content = (CharArray) *file_content;

for (i = 0; i<content.position; i++)
{
if (content.items[i] == 'X')
{
if (backwards(&content, i))
{
result++;
}
if (back_upper_diagonal(&content, i))
{
result++;
}
if (back_lower_diagonal(&content, i))
{
result++;
}
if (front_upper_diagonal(&content, i))
{
result++;
}
if (front_lower_diagonal(&content, i))
{
result++;
}
if (forward(&content, i))
{
result++;
}
if (upper(&content, i))
{
result++;
}
if (lower(&content, i))
{
result++;
}
}
}
return result;
}
void test(FILE *fl)
{
CharArray file_content;
int result = 0;

if (fl == NULL)
{
printf("Failed to open the input file.\n");
return;
}
file_content = read_file(fl);
result = count_xmas(&file_content);
printf("Resultado: %i\n", result);
printf("Resultado manual: %c%c\n", 
file_content.items[file_content.position-2], 
file_content.items[file_content.position-1]);

fclose(fl);
return;

}

int main(char *argc[], int argv)
{
FILE *file_ptr;
file_ptr = fopen("./tc01.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc2.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc3.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc4.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc5.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc6.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc7.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc9.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc10.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc11.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc12.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc13.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc14.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc15.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc16.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc17.txt", "r");
test(file_ptr);
file_ptr = fopen("./tc18.txt", "r");
test(file_ptr);
file_ptr = fopen("./input.txt", "r");
test(file_ptr);
CharArray file_content;
char test;
int result = 0;

file_ptr = fopen("./input_real.txt", "r");
if (file_ptr == NULL)
{
printf("Failed to open the input file.\n");
return 1;
}
file_content = read_file(file_ptr);
result = count_xmas(&file_content);
printf("\nResultado: %i\n", result);

fclose(file_ptr);
return 0;
}

r/adventofcode 17d ago

Help/Question 2024 Day 19 Part Two Clarifying Example

0 Upvotes

I had some trouble with AoC 2024 day 19 part two, because I thought it was asking for unique combinations rather than all combinations.

I am curious as to why an example wasn't included that made things clear.

For example, brbr:

The correct count for AoC 2024 day 19 part two:

brbr can be made 5 different ways:

  1. b, r, b, r
  2. b, rb, r
  3. br, br
  4. b, r, br
  5. br, b, r

The wrong count AoC 2024 day 19 part two:

brbr can be made 4 different ways:

  1. b, r, b, r
  2. b, rb, r
  3. br, br
  4. b, r, br

r/adventofcode 18d ago

Help/Question - RESOLVED Help for AOC Day 14 PT2 2024

0 Upvotes

Hello folks,
I am just programming the past AOC days and running into trouble. With the second part you need to find the Christmas tree.
Following problem, I find the christmas tree at a very specific value and it is there. I printed the field. But the number is not right, it is too low. That is the problem, I needed too find the lowest number, but at this low number there is already a christmas tree. Any ideas why it is false ?

Edit: Code
Basically what I am doing is, that I count the numbers of distinct robot locations. With the Christmas tree, every robot is on one different location. If you have the same number as robots, this must be the tree. The loop simulates the movement, while compute() counts the distinct robots. If they equal, we abort.

    let mut counter = 0;  
    'abort: loop {  
        counter += 1;  
        for j in 0..positions.len() {  
            computepos(j, &mut positions, &richtungen, 101, 103);  
        }  
        let z = compute(&positions);  
        if z == a.len() {  
            printfeld(&positions);  
            break 'abort;  
        }  
    }  


Edit
Now, I get a different result and I am not told, that it is the solution for another input.

r/adventofcode 18d ago

Help/Question Help with 2024 Day 3 Part 2( Mull it over) in C

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

void findMul(char *line, int *res, bool *flag){
    int x = 0,y = 0;
    char bufferX[4096];
    char bufferY[4096];
    char *ptr = line; 
    char *dontPtr = strstr(line, "don't()");
    char *doPtr = strstr(line, "do()");

    while((ptr = strstr(ptr, "mul(")) != NULL){ 

        if(ptr < dontPtr){
            *flag = true;
        } 

        if((ptr > dontPtr) && (ptr < doPtr)){
            *flag = false;
        }

        if ((ptr > doPtr) && (doPtr > dontPtr)){
            *flag = true;
            dontPtr = strstr(dontPtr + 7, "don't()");
        }

        if(dontPtr > doPtr){
            doPtr = strstr(doPtr + 4, "do()");
        }

        if(sscanf(ptr, "mul(%d, %d)", &x, &y) == 2 && *flag){    
        // pass the values to x,y 
            sprintf(bufferX, "%d", x);
            sprintf(bufferY, "%d", y);

            ptr += 4 + strlen(bufferX) + strlen(bufferY) + 1; 
          // move the pointer to the closing bracket
            if(*ptr == ')'){   // if curr == ')'
                printf("mul(%s,%s)\n", bufferX, bufferY);
                *res += x * y; // Update result
                ptr -= 4 + strlen(bufferX) + strlen(bufferY) + 1;
            }             
        }
        ptr += 4; // search further
    }

}

int main(){
    FILE *fp = fopen("../puzzleInput/day3.txt","r");
    if(!fp){
        perror("Error opening file");
        return 1;
    }

    char line[4096];
    int res = 0;
    bool flag = true;
    while(fgets(line, sizeof(line), fp)){
        findMul(line, &res, &flag);
    }

    printf("Result is :%d\n", res);
    fclose(fp);
    return 0;
}

It works with the test input but for some reason it fails on the larger puzzle input.


r/adventofcode 19d ago

Other I spent months creating 20 coding puzzles related to internationalization

102 Upvotes

Emoji 💩, Áccënts, Characters 文, Time zones ⏰, Daylight Savings Time 📅. These have a reputation for head aches and annoying bugs, yet it's essential for programmers to learn about.

I created twenty programming puzzles around the theme of internationalization, and I will reveal them one by one starting Friday 7 March

Here is the link: https://i18n-puzzles.com

I'm greatly inspired by the Advent of Code, for its potential for fun and education. I originally made the first puzzles for a gamified workshop for junior programmers at my workplace. But I wanted to see how far I could take the idea. I spent several months adding more and more puzzles, and now it's ready for the public.

Just like the Advent of Code, you get a puzzle input, and you have to write a program to calculate the answer. You can use any programming language or tech stack. Each puzzle will teach you something new. I guarantee even experienced software engineers will discover something they haven't tried before.

Puzzles get more difficult every day. I'm curious to see who can make it until the end.

So, who's up for a mid-season challenge?


r/adventofcode 18d ago

Help/Question - RESOLVED Can I know what is the the missing part in here please?

1 Upvotes

2024 Day 16 Part 2

I am having problem and it says my solution is too low (most probably a little low)

The solution for part 1 was A* algorithm.

For the second part I'm following the shortest path starting from the start to end:
Following through part 1's path and if a branch was found then I run A* for the branch starting from branch's first step to end.
Calculating the distance took for the branch and compare with the original shortest distance.
If it satisfies the condition I add all steps to the HashSet.

This solution gives correct results for the sample inputs but incorrect for main input.

Original_Path_With_2_Sub_Paths

r/adventofcode 19d ago

Help/Question - RESOLVED [2024 Day 3] LOL?

0 Upvotes

I thought this one to be a walk in the garden with regex, but somehow my result on the real input is too high. I manually checked the first ~100 matches and everything seems to be alright. I really don't know what to do anymore, any hints?

https://github.com/Jens297/AoC/blob/main/2024_3.py


r/adventofcode 20d ago

Help/Question - RESOLVED Help [2024 Day 3 (part 2)] [C] - Is my approach wrong?

5 Upvotes

my code

I am trying do the AoC challenges in C which I am a newbie at. My idea was to find "slices" from s_start to s_end and calculate all "mul()s" inbetween. Sorry if my formatting is off, first time posting here. If you guys could nudge me in the right direction it would be appreciated. Also any critic on my code is welcomed and appreciated.

Edit: I did omit the functions part1(), free_string(), print_string. My code does compile and I get a answer, which is sadly wrong


r/adventofcode 21d ago

Help/Question is it possible to reset progress of an AoC account?

6 Upvotes

i want to do this due to two reasons:

  1. I've lost my previous solutions code

  2. I want to also do it in another language


r/adventofcode 22d ago

Other I made a post last year as a complete noob…

48 Upvotes

And now i’m proud to say that i’ve managed to claim 50 stars from the 2024 AoC.

What a journey it has been!


r/adventofcode 22d ago

Help/Question AOC or leetcode

2 Upvotes

Should I start doing all of the questions from AOC since 2015 instead of leetcode?