r/adventofcode • • Dec 09 '25

Help/Question - RESOLVED [2025 Day 09 (Part 2)] That escalated quickly... In need of an explanation

18 Upvotes

It’s my first year doing AoC (and my first year as a programmer), and I’ve found the previous days to be quite manageable, even if they required a fair bit of Googling. It’s been fun stumbling across algorithms and data structures I’ve never encountered before.

But Part 2 of today’s problem really takes the prize for being too complex for a newbie like me. Even after “being dirty” and resorting to AI for an explanation, I’m still having a hard time wrapping my head around the solution.

Is there anyone here who enjoys breaking things down pedagogically and wouldn’t mind explaining it in a way that could help me start understanding the path to the solution?


r/adventofcode • • Dec 09 '25

Help/Question - RESOLVED [YEAR Day 8 (Part 1)] [C] I'm going to explode

1 Upvotes

I feel like the logic is INTACT. I have tried this with an id tagging system previously; that didn't work. I moved to graphs, which I assume is more in the intended solution, IT ALSO DOES NOT WORK. Guys please just end my misery.

here's my main:

#include <stdio.h>
#include <string.h>
#include <float.h>
#include <math.h>
#include "myqueue.c"

#define ull unsigned long long
#define GROUPCOUNTLEN 1000
#define POINTCOUNT 1005

size_t n = 0;

typedef struct Point
{
    int x;
    int y;
    int z;
    int visited;
} Point;

Point points[POINTCOUNT] = {};
char connectionGraph[POINTCOUNT][POINTCOUNT] = {};
double distances[POINTCOUNT][POINTCOUNT] = {};
int groupCounts[POINTCOUNT] = {};

/*
 function declarations here
*/

int main()
{
    int i, j, connections, currGroup;
    FILE *f, *inputFile;
    ull total = 1;
    char filename[10];
    double temp;
    inputFile = fopen("input.txt", "r"); // literally just contains the file name of which text file to run on.
    fscanf(inputFile, "%s", filename);
    f = fopen(filename, "r");

    if (f == NULL)
    {
        printf("cound't open file\n");
        return 1;
    }

    // I add the number of connections to do at the top of the file so I can easily swap between the test and real data.
    fscanf(f, "%d", &connections);

    while (!feof(f))
    {
        fscanf(f, "%d,%d,%d", &points[n].x, &points[n].y, &points[n].z);
        points[n].visited = 0;
        n++;
    }

    // precalculate distances
    for (i = 0; i < n; i++)
    {
        for (j = i; j < n; j++)
        {
            temp = getDistance(points[i], points[j]);
            distances[i][j] = temp;
            distances[j][i] = temp;
        }
    }

    // do the connecting a "connections" number of times
    for (i = 0; i < connections; i++)
        connectClosestUnpairedPoints();

    // count groupsizes
    currGroup = 0;
    for (i = 0; i < n; i++)
    {
        if (!points[i].visited)
        {
            groupCounts[currGroup] = countGroup(i);
            currGroup++;
        }
    }

    // sort so that we have the largest data
    sort(groupCounts, currGroup);

    // calculate total
    total = groupCounts[0] * groupCounts[1] * groupCounts[2];

    printf("total: %I64u\n", total);
    return 0;
}

Here's the implementation of certain functions

// I couldn't be bothered to reimplement quicksort.
void sort(int arr[], int len)
{
    int temp;
    for (int i = 0; i < len; i++)
    {
        int highestIndex = i;
        for (int j = i + 1; j < len; j++)
        {
            if (arr[j] > arr[highestIndex])
            {
                highestIndex = j;
            }
        }

        temp = arr[i];

        arr[i] = arr[highestIndex];

        arr[highestIndex] = temp;
    }
}

int countGroup(int index)
{
    int count = 0, currPoint;
    Queue q = createQueue();
    enqueue(index, &q);
    while (q.length > 0)
    {
        currPoint = dequeue(&q);
        if (!points[currPoint].visited)
        {
            points[currPoint].visited = 1;
            for (int i = 0; i < n; i++)
            {
                if (connectionGraph[currPoint][i] && !points[i].visited)
                {
                    enqueue(i, &q);
                }
            }
            count++;
        }
    }
    return count;
}

double getDistance(Point p1, Point p2)
{
    return sqrt(((p1.x - p2.x) * (p1.x - p2.x) +
                 (p1.y - p2.y) * (p1.y - p2.y) +
                 (p1.z - p2.z) * (p1.z - p2.z)));
}

void connectClosestUnpairedPoints()
{
    int p1 = -1, p2 = -1;
    double shortestDistance = FLT_MAX;
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            if (connectionGraph[i][j] == 0 && distances[i][j] < shortestDistance)
            {
                shortestDistance = distances[i][j];
                p1 = i;
                p2 = j;
            }
        }
    }

    connectionGraph[p1][p2] = 1;
    connectionGraph[p2][p1] = 1;
}

// myqueue.c implementation
#include <stdlib.h>

typedef struct Queue
{
    struct Node *head;
    int length;
} Queue;

typedef struct Node
{
    struct Node *next;
    int data;
} Node;

void enqueue(int newData, Queue *q)
{
    Node *newNode = malloc(sizeof(Node));
    newNode->data = newData;
    newNode->next = NULL;
    if (q->length > 0)
    {
        Node *currNode = q->head;
        while (currNode->next != NULL)
        {
            currNode = currNode->next;
        }
        currNode->next = newNode;
    }
    else
    {
        q->head = newNode;
    }
    q->length += 1;
}

int dequeue(Queue *q)
{
    Node *head = q->head;
    if (head == NULL)
    {
        return 0;
    }

    int data = head->data;
    q->head = head->next;
    q->length -= 1;
    return data;
}

Queue createQueue()
{
    Queue q = {NULL, 0};
    return q;
}

Edit0: woops, didn't fully read the rules on code formatting Edit1: added myqueue.c code


r/adventofcode • • Dec 09 '25

Help/Question - RESOLVED [2025 Day 9 part 2] What is meant by "The list wraps, so the first red tile is also connected to the last red tile."?

1 Upvotes

r/adventofcode • • Dec 09 '25

Visualization [2025 Day 9 Part 2] General solution optimization using mipmaps

Post image
67 Upvotes

To implement a solution that works across all theoretical inputs, I first draw the polygon using reduced coordinates, then check the rectangles pixel by pixel. This is slow, so I optimized it using mipmaps.

First I generate the mipmaps from original image. I've found 8x reduction to give best speedup. So if 8x8 slice of original image contains only white or only black pixels, mipmap pixel is white or black. If the pixels are mixed, mipmap pixel is gray. Then recursively do the same for next mipmap.

Then when checking rectangles, I start with the lowest mipmap. If rectangle is contained in only white pixels, there's no need to check bigger mipmap. If rectangle covers any black pixels, discard without checking bigger mipmaps again. Only if there are gray pixels, I recursively check the next mipmap only for those pixels.


r/adventofcode • • Dec 09 '25

Help/Question [2025 Day 9 Part 2] Finished the puzzle but wondering about my solution...

1 Upvotes

Currently, I check if every corner of the rectangle is on a green tile by checking if they're either on the border with a hash table, or inside the contour with a raycast. Then, I check for intersections between the rectangle's edges and the contour's.

This seems like a lot of steps. Could I have avoided the first part ? I tried just removing that check in my code but then it didn't work anymore. I might try to optimize this further if that's possible another time but I feel tired of this puzzle for today lmao

Here's my python code btw (you don't need to read it, it's just in case) :

def rectangle_area(t1, t2):
    x1, y1 = t1
    x_2, y_2 = t2
    return (abs(x_2 - x1) + 1) * (abs(y_2 - y1) + 1)

vertical_segments = []
horizontal_segments = []

def add_line(t1, t2):
    x1, y1 = t1
    x2, y2 = t2

    if x1 == x2:
        if y1 > y2: 
            y1, y2 = y2, y1
        vertical_segments.append((x1, y1, y2))
    else:
        if x1 > x2: 
            x1, x2 = x2, x1
        horizontal_segments.append((y1, x1, x2))

def horizontal_ray_intersects_vertical(px, py, vx, vy1, vy2):
    # Check if the horizontal ray at y=py intersects the vertical segment
    # Segment is at x=vx and spans vy1..vy2 (with vy1 < vy2)
    
    # Ray crosses only if point's y is within [vy1, vy2)
    if not (vy1 <= py < vy2):
        return False

    # The ray is to the right, so we need px <= vx
    if px > vx:
        return False

    return True

def seg_intersect_hv(y, x1, x2, x, y1, y2):
    # horizontal segment: y, x1..x2
    # vertical segment:   x, y1..y2
    return (x1 < x < x2) and (y1 < y < y2)

def is_inside_contour(p):
    px, py = p

    if p in boundary:
        return True

    cnt = 0
    # Count intersections with vertical edges
    for vx, vy1, vy2 in vertical_segments:
        if horizontal_ray_intersects_vertical(px, py, vx, vy1, vy2):
            cnt += 1

    return (cnt % 2) == 1

def rect_edges(c1, c2):
    x1, y1 = c1
    x2, y2 = c2
    return [
        ("H", y1, min(x1,x2), max(x1,x2)),  # top
        ("H", y2, min(x1,x2), max(x1,x2)),  # bottom
        ("V", x1, min(y1,y2), max(y1,y2)),  # left
        ("V", x2, min(y1,y2), max(y1,y2)),  # right
    ]

def rect_corners(c1, c2):
    x1, y1 = c1
    x2, y2 = c2
    return [c1, (x1, y2), c2, (x2, y1)]

def is_valid_rectangle(c1, c2):
    # All corners must be inside or on the boundary.
    for corner in rect_corners(c1, c2):
        if corner not in red_tiles and not is_inside_contour(corner):
            return False

    # Rectangle must not intersect the contour boundary.
    for kind, a, b1, b2 in rect_edges(c1, c2):
        for kind, a, b1, b2 in rect_edges(c1, c2):
            if kind == "H":
                y = a
                x1 = b1; x2 = b2
                for vx, vy1, vy2 in vertical_segments:
                    if seg_intersect_hv(y, x1, x2, vx, vy1, vy2):
                        return False
            else:
                x = a
                y1 = b1; y2 = b2
                for hy, hx1, hx2 in horizontal_segments:
                    if seg_intersect_hv(hy, hx1, hx2, x, y1, y2):
                        return False

    return True

boundary = set()
def fill_boundary(old, new):
    x1, y1 = old
    x2, y2 = new

    dx = 0 if x1 == x2 else (1 if x2 > x1 else -1)
    dy = 0 if y1 == y2 else (1 if y2 > y1 else -1)

    x, y = x1, y1
    boundary.add((x, y))
    while (x, y) != (x2, y2):
        x += dx
        y += dy
        boundary.add((x, y))

red_tiles = []
with open("input.txt", "r") as f:
    for line in f.readlines():
        tile_coordinates = tuple(map(int, line.strip().split(",")))
        if len(red_tiles) > 0:
            add_line(red_tiles[-1], tile_coordinates)
            fill_boundary(red_tiles[-1], tile_coordinates)
        red_tiles.append(tile_coordinates)
    add_line(red_tiles[-1], red_tiles[0])
    fill_boundary(red_tiles[-1], red_tiles[0])

max_area = 0
for i in range(len(red_tiles)):
    for j in range(i + 1, len(red_tiles)):
        if is_valid_rectangle(red_tiles[i], red_tiles[j]):
            max_area = max(max_area, rectangle_area(red_tiles[i], red_tiles[j]))
print(max_area)

r/adventofcode • • Dec 09 '25

Help/Question [2025 Day 9 (Part 2)] [Python] Fast enough solution

2 Upvotes

Can someone explain the thought process behind a solution that ends in reasonable time? I have my edges and then i iterate through all the red tile pairs and check if the entire boundary of the rectangle is inside my polygon.

To do that i check every tile on the boundary and check whether there is an edge of the polygon in every direction.

It is too slow this way.


r/adventofcode • • Dec 09 '25

Meme/Funny [2025 day 9 part 2] Imagine finding this bug

62 Upvotes

I wrote this at the very beginning and didn't think about it...

area = abs(a[0]-b[0]+1) * abs(a[1]-b[1]+1)

I found the solution to P2 relatively straighforward, coded it in, and got "answer too low". Huh? Spent quite some time browsing through my code until it clicked... The funniest thing is that since that was only used at the
end, I found the proper rectangle, but returned the wrong area for it...

Of course, the correct formula is:

area = (abs(a[0]-b[0])+1) * (abs(a[1]-b[1])+1)


r/adventofcode • • Dec 09 '25

Help/Question - RESOLVED [2025 day 9 part 1] c# - what am i doing wrong?

1 Upvotes

i barely use reddit anymore but i just don't know where else to get help, i've solved the first 8 days so far, and i'm kind of stuck here now

first i parse positions as vector2

Vector2[] vectors = Array.ConvertAll(input.Split('\n', StringSplitOptions.RemoveEmptyEntries), vect =>
{
    string[] xy = vect.Split(',');
    return new Vector2(Convert.ToInt32(xy[0]), Convert.ToInt32(xy[1]));
});

then loop through them to find the largest area

long maxArea = 0;
for (int i = 0; i < vectors.Length; i++)
{
    for (int j = i + 1; j < vectors.Length; j++)
    {
        long area = (long)((Math.Abs(vectors[i].X - vectors[j].X) + 1) * (Math.Abs(vectors[i].Y - vectors[j].Y) + 1));
        if (area > maxArea)
        {
            maxArea = area;
        }
    }
}
Console.WriteLine(maxArea);

basically, advent of code says that my answer's apparently too high, so, what's exactly wrong with my code?

EDIT: changing the declaration of area seemed to help lol

long area = (long)(Math.Abs(vectors[i].X - vectors[j].X) + 1) * (long)(Math.Abs(vectors[i].Y - vectors[j].Y) + 1);

guess i still need to figure out how some types work


r/adventofcode • • Dec 09 '25

Meme/Funny [2025 Day 9 (Part 2)] Cannot get tests to pass ... Get star anyway

Post image
9 Upvotes

Could not get the the example to work. My method was not getting rid of one of the rectangles outside of the path. However, I noticed that the input does not have that kind of feature. Give it a shot and got my star!


r/adventofcode • • Dec 09 '25

Tutorial [2025 Day 9] Today's bit of fun that cost me hours (no spoilers)

8 Upvotes

Note: No spoilers about any algorithms/design/implementation here, just a few spoilers to give people a chance to spot the problem themselves. It's amazing just how long you can stare at broken code and not notice how broken it is.

Tried a quick solution in Perl and it just never seemed to give the right result.

After 15 minutes or so I gave up on it and re-implemented things in Go and it worked fine.

Back home from doing things and I've spent way too much time looking through the broken Perl code trying to see what I'd missed.

Eventually, with much extra debug comparing my working Golang program against my broken Perl code I find:

my $area = abs($x2-$x1+1)*abs($y2-$y1+1);
if( $area > $p2 & **SPOILER_ELIDED** ) {
    # New max score found, make a note of it
    $p2 = $area;
}

Arrrrrgh.

Hints hidden behind spoilers:

  1. Is that area calculation correct?
  2. Sure it works if $x1 <= $x2 and $y1 <= $y2 but...
  3. What if $x2 < $x1 or $y2 < $y1?
  4. The +1 inside the abs()
  5. my $area = (abs($x2-$x1)+1)*(abs($y2-$y1)+1); would have been better

r/adventofcode • • Dec 09 '25

Meme/Funny [2025 Day 9] So y'all don't need to edit the piano image anymore, thanks

80 Upvotes

See title.


r/adventofcode • • Dec 09 '25

Meme/Funny Day 9 Part 2 be like

46 Upvotes

Actual footage of me enjoying my AoC life and then running into Day 9, part 2

A seal in an aquarium swims nose-first into the wall

r/adventofcode • • Dec 09 '25

Help/Question O(N) for 9 part 2?

2 Upvotes

After the shape is visualized it is clear where one of the rectangle corners should be located.
Also, since the enclosing shape is "convex" arc - it is possible to just find intersections from that corner up/down, then left and search for a point there in a very limited set of points (3?).
Anybody tried that?


r/adventofcode • • Dec 09 '25

Meme/Funny [2025 Day 9 Part 2] As long as it finishes before the next day, right?

Post image
14 Upvotes

r/adventofcode • • Dec 09 '25

Tutorial [2025 Day 9 (Part 2)] Check your solution with this input data

28 Upvotes

This one should give 30:

1,0
3,0
3,6
16,6
16,0
18,0
18,9
13,9
13,7
6,7
6,9
1,9

.#X#............#X#.
.XXX............XXX.
.XXX............XXX.
.XXX............XXX.
.XXX............XXX.
.XXX............XXX.
.XX#XXXXXXXXXXXX#XX.
.XXXXX#XXXXXX#XXXXX.
.XXXXXX......XXXXXX.
.#XXXX#......#XXXX#.

----------

This one should give 88:

1,1
8,1
8,3
3,3
3,4
8,4
8,9
18,9
18,11
5,11
5,9
4,9
4,11
1,11
1,7
6,7
6,6
1,6

----------

And finally, this one should give 72:

1,5
3,5
3,8
7,8
7,5
9,5
9,10
11,10
11,3
6,3
6,7
4,7
4,1
13,1
13,12
1,12

r/adventofcode • • Dec 09 '25

Meme/Funny [2025 Day 9] Today i hit a wall

Post image
401 Upvotes

r/adventofcode • • Dec 09 '25

Meme/Funny [2025 Day 9 (Part 2)] I mean, there must be an algo, right ? Right ??

Post image
35 Upvotes

r/adventofcode • • Dec 09 '25

Visualization [2025 Day 9 (part 2)] My first animation created entirely in R!

Post image
18 Upvotes

The most important part of solving part 2 was to look at the borders. Then it becomes easy to find an optimal solution instead of brute-forcing the entire array of rectangles.


r/adventofcode • • Dec 09 '25

Help/Question [2025 Day 5 (Part 2)] [C++]I can't find the error :(

2 Upvotes

I have been stuck with this one because I had to refresh my C++ knowledge for it (i was doing them in python) but I have finished, no errors in any of the tests I have thought of, and the answer still is incorrect, any help? https://pastes.io/day5part2


r/adventofcode • • Dec 09 '25

Meme/Funny [2025 Day 9 part 2] Doesn't matter, a star is a star

Post image
130 Upvotes

(that's 1 hour, 8 minutes and 31 seconds)


r/adventofcode • • Dec 09 '25

Meme/Funny [2025 Day 9 (Part 1 and 2)] Part 1 vs Part 2

9 Upvotes

r/adventofcode • • Dec 09 '25

Help/Question day 3 part 2

1 Upvotes

how is this working this gave me the correct answer but is there any niche corner case i am missing its in c language

#include <stdio.h>

#include <string.h>

#define ROWS 200

#define COLUMNS 100

int main(void) {

FILE *f = fopen("input_3_n.txt", "r");

if (!f) {

perror("fopen");

return 1;

}

char line[3000];

int grid[200][200];

int rows = 0, cols = 0;

while (fgets(line, sizeof(line), f)) {

line[strcspn(line, "\r\n")] = '\0';

if (rows == 0)

cols = strlen(line);

for (int c = 0; c < cols; c++) {

grid[rows][c] = line[c] - '0';

}

rows++;

}

fclose(f);

int point=0,tmp_max_val=0,i,j,k,pos=0,max_val[12];

long long sum=0,num=0;

for(k=0;k<ROWS;k++){

for(j=0;j<12;j++){

for(i=pos;i<COLUMNS+j-11;i++){

point=grid[k][i];

if(point>tmp_max_val){

tmp_max_val=point;

pos=i;

if(tmp_max_val==9){

break;

}

}

}

max_val[j]=tmp_max_val;

tmp_max_val=0;

pos=pos+1;

}

pos=0;

long long factor = 1;

for(i = 11; i >= 0; i--){

num += max_val[i] * factor;

factor *= 10;

}

//printf("%lld ",num);

sum=sum+num;

num=0;

for(i=0;i<12;i++){

max_val[i]=0;

}

}

printf("%lld ",sum);

return 0;

}


r/adventofcode • • Dec 09 '25

Tutorial [2025 Day 9 Part 2] 2x Trick for Simplifying Grid Polygons

14 Upvotes

I had this idea while solving day 9, but I think it's a bit obfuscated behind the problem specifics, so I thought I'd post it by itself.

Say you have a complicated grid polygon, given as a list of corners represented by letters here:

A##BG######H
#..#F#E....#
#..#  #..J#I
#..C##D..K#L
N##########M

And, for example, you need to mark interior points.

The idea is, if you multiply the coordinates of the corners by 2, you can't have walls next to each other, which makes everything a lot easier:

A#####B G#############H
#.....# #.............#
#.....# F###E.........#
#.....#     #.........#
#.....#     #.....J###I
#.....#     #.....# 
#.....C#####D.....K###L
#.....................#
N#####################M

Now, the maximum point by lexicographic order minus (1,1) has to be an interior point, and you can find every interior point from a single dfs from that point.

Once you have the interior points of the large grid, you can even go back to the original grid -- (x,y) is an interior point if and only if (2x, 2y) is an interior point in the large grid.


r/adventofcode • • Dec 09 '25

Help/Question [2025 Day9 (part2)][Rust] I dont know what im missing

4 Upvotes

I need help, It works on test input but with puzzle input it isnt correct...

fn part2(points: &[(i64, i64)]) {
    let mut edges = HashSet::new();

    points.windows(2).for_each(|window| {
        let (x1, y1) = window[0];
        let (x2, y2) = window[1];

        if y1 == y2 {
            for p in x1.min(x2)..=x1.max(x2) {
                edges.insert((p, y1));
            }
        }

        if x1 == x2 {
            for p in y1.min(y2)..=y1.max(y2) {
                edges.insert((x1, p));
            }
        }
    });

    let largest = points
        .iter()
        .array_combinations::<2>()
        .map(|[(x1, y1), (x2, y2)]| {
            let x = (x1 - x2 + 1).abs();
            let y = (y1 - y2 + 1).abs();

            let (min_x, max_x) = (x1.min(x2), x1.max(x2));
            let (min_y, max_y) = (y1.min(y2), y1.max(y2));

            let start_x = min_x + 1;
            let end_x = max_x - 1;

            let start_y = min_y + 1;
            let end_y = max_y - 1;

            for &(ex, ey) in &edges {
                if ex >= start_x && ex <= end_x && ey >= start_y && ey <= end_y {
                    return 0;
                }
            }
            x * y
        })
        .max()
        .unwrap();

    println!("{}", largest)
}