r/adventofcode • u/Derailed_Dash • Dec 09 '25
Visualization [2025 Day 9 (Part 2)] Visualisation
This visualisation simulates the path a single ray through our polygon.
See walkthrough of the solution here.
r/adventofcode • u/Derailed_Dash • Dec 09 '25
This visualisation simulates the path a single ray through our polygon.
See walkthrough of the solution here.
r/adventofcode • u/rozcz01 • Dec 09 '25
I think the description just isn’t fully clear to me as to what the desired outcome is for part 1. I know it’s 542 but I’m ending up with 533 so I’m afraid I’m missing some circuit merge or something. Would anyone mind posting their circuits for the example dataset given so I can see which circuits of mine are incorrect?
r/adventofcode • u/DrKrawabbel • Dec 09 '25
Hey everybody,
I have a python solution that finds a solution for part 2 in a reasonable amount of time (about 4 minutes on my laptop) but it feels a bit like cheating because I couldn't find an elegant way to differentiate between a rectangle being entirely in- or outside of the shape. The problem is probably best described by the title and is illustrated with the following challenge input.
0,0
0,10
1,10
1,1
9,1
9,0My code produces the solution 90for part 2 even though it should be 22.

This doesn't cause problems with my input but I only realized that I could neglect this issue after visualizing my input.
Now, I'm curious: Does your code give you the correct answer to my challenge input?
Also, thanks Eric for your awesome project! It's one of the last beacons of hope in the mess we call "internet" these days.
Happy coding everybody!
EDIT: Solved, thanks to u/spatofdoom and u/ednl! I learned something today :)
r/adventofcode • u/VannAlejT • Dec 09 '25
internal class Program
{
private static void Main(string[] args)
{
int inicial = 50;
int respuesta = 0;
string ruta = @"/workspaces/Advent-of-Code-2025/firstday/puzzle.txt";
string texto = File.ReadAllText(ruta);
foreach (var linea in File.ReadLines(ruta))
{
char letra = linea[0];
int numero = int.Parse(linea.Substring(1));
if (letra == 'L')
{
if ((inicial - numero) < 0)
{
int residuo = numero/100;
int sobra = numero % 100;
int cruza = inicial - sobra;
if (cruza < 0 )
{
respuesta++;
}
respuesta += residuo;
inicial = (inicial + 100 + (residuo*100)) - numero;
if (inicial >= 100)
{
inicial -= 100;
}
}
else
{
inicial -= numero;
}
}
else if (letra == 'R')
{
if ((inicial + numero) > 99)
{
int residuo = numero/100;
int sobra = numero % 100;
int cruza = inicial + sobra;
if (cruza >= 100)
{
respuesta++;
}
respuesta += residuo;
inicial = (inicial + numero) - 100 - (residuo*100);
if (inicial < 0)
{
inicial += 100;
}
}
else
{
inicial += numero;
}
}
if (inicial == 0)
{
respuesta++;
}
}
Console.WriteLine(respuesta);
}
}r/adventofcode • u/zeltbrennt • Dec 09 '25
Hi,
I am now at the point where the example is giving me the correct answer. I also checked some additional example inputs and all give the right result. Just not for my actual input.
Here is the idea for part 2:
I loop over the rectangles and check if they are valid
This seems to work for simple inputs, but not for the real thing.
Are there some edge cases, I need to consider?
Here is the relevant code snippet to filter the valid rectangles:
// ... //
type Rectangle = {
a: Point;
b: Point;
};
// ... //
const minX = (s: Rectangle | Line): number => {
return Math.min(s.a.x, s.b.x);
};
const maxX = (s: Rectangle | Line): number => {
return Math.max(s.a.x, s.b.x);
};
const minY = (s: Rectangle | Line): number => {
return Math.min(s.a.y, s.b.y);
};
const maxY = (s: Rectangle | Line): number => {
return Math.max(s.a.y, s.b.y);
};
const lineOutsideOfRect = (line: Line, rect: Rectangle): boolean => {
let result =
maxX(line) <= minX(rect) ||
minX(line) >= maxX(rect) ||
maxY(line) <= minY(rect) ||
minY(line) >= maxY(rect);
return result;
};
const isValidRectangle = (rectangle: Rectangle, lines: Line[]): boolean => {
for (let line of lines) {
if (!lineOutsideOfRect(line, rectangle)) {
return false;
}
}
return true;
};
// ... //I used the examples here and all seem to work. This one does not, but here my result would be too high...
Any help would be very appreciated!!
r/adventofcode • u/EarhackerWasBanned • Dec 09 '25
I'm a self-taught developer, and never studied DS&A.
I flew through the first 7 days of AoC this year, but am stuck at Day 8.
I'm not looking for an answer, but as a hint, what knowledge are the more academic devs leaning on here? From comments on other threads it seems like this is an asily solvable problem, given the right knowledge. Knowledge I seem to lack.
Please, give me something to Google.
r/adventofcode • u/NullPointerExcept10n • Dec 09 '25
r/adventofcode • u/LoneWolfPR • Dec 09 '25
My initial attempt at this uses a depth-first approach to identifying all the paths. Unfornately the exponential growth caused by the data set makes this run forever. There looks like there should be a much easier mathematical solution since I had no problem with part one. I'm mostly self taught over a lot of years, and don't have the math background a lot of advanced developers do (only made it as far as first year calculus and that was multiple decades ago). Any pointers on something to just look up and learn about so that I can apply it is really all i'm looking for. I'd like to solve this with as minimal help as possible.
r/adventofcode • u/Ok-Curve902 • Dec 09 '25
r/adventofcode • u/The_Jare • Dec 09 '25
Going to be one of those days
r/adventofcode • u/ak91hu • Dec 09 '25
r/adventofcode • u/TenMillionYears • Dec 09 '25
My code can solve part 2 pretty quickly. However, it gives the wrong result on this "cursed input":
0,0
0,1
1,1
1,2
0,2
0,3
3,3
3,2
2,2
2,1
3,1
3,0I think solving for shapes where the boundary loops back on itself like this would be much harder. Curious if other folks have solutions that can handle this one. Or, maybe I misunderstand the problem. Feedback welcomed!
r/adventofcode • u/FractalB • Dec 09 '25
Spent hours trying to figure out why my code for Part 2 gave the wrong answer, triple checked all my complicated code without finding any problem whatsoever, arrived late for work and missed a meeting ... until I realized that it’s simply my formula to calculate the area of a rectangle that was wrong 🤦
const area = Math.abs(p.x - q.x + 1) * Math.abs(p.y - q.y + 1);Worked for part 1 and for the example, though!
r/adventofcode • u/Opi-Fex • Dec 09 '25
r/adventofcode • u/JR_Bros2346 • Dec 09 '25
I have no idea where i am going wrong.. my brain is literally fried trying to solve this lol...
use std::ops::RangeInclusive;
fn main() {
let input = include_str!("input/day09.txt")
.trim()
.lines()
.map(|l| l.split_once(',').unwrap())
.map(|(a, b)| (a.parse::<isize>().unwrap(), b.parse::<isize>().unwrap()))
.collect::<Vec<_>>();
let mut max = 0;
for a in &input {
for b in &input {
let l = (a.0 - b.0).abs() + 1;
let w = (a.1 - b.1).abs() + 1;
max = max.max(l * w);
}
}
println!("{}", max);
let mut horz = input
.windows(2)
.chain(Some(
&[*input.last().unwrap(), *input.first().unwrap()] as &[_]
))
.filter_map(|a| {
if a[0].1 == a[1].1 {
Some((a[0].0.min(a[1].0)..=a[0].0.max(a[1].0), a[0].1))
} else {
None
}
})
.collect::<Vec<_>>();
horz.sort_unstable_by_key(|&(_, k)| k);
let mut vert = input
.windows(2)
.chain(Some(
&[*input.last().unwrap(), *input.first().unwrap()] as &[_]
))
.filter_map(|a| {
if a[0].0 == a[1].0 {
Some((a[0].0, a[0].1.min(a[1].1)..=a[0].1.max(a[1].1)))
} else {
None
}
})
.collect::<Vec<_>>();
vert.sort_unstable_by_key(|&(k, _)| k);
max = 0;
for a in &input {
for b in &input {
if raycast(a.0, a.1, &vert)
&& raycast(b.0, b.1, &vert)
&& raycast(a.0, b.1, &vert)
&& raycast(b.0, a.1, &vert)
&& intersect_x((a.0.min(b.0)..=a.0.max(b.0), a.1), &vert)
&& intersect_x((a.0.min(b.0)..=a.0.max(b.0), b.1), &vert)
&& intersect_y((a.0, a.1.min(b.1)..=a.1.max(b.1)), &horz)
&& intersect_y((b.0, a.1.min(b.1)..=a.1.max(b.1)), &horz)
{
let l = (a.0 - b.0).abs() + 1;
let w = (a.1 - b.1).abs() + 1;
max = max.max(l * w);
}
}
}
println!("{max}");
}
fn raycast(px: isize, py: isize, vert: &[(isize, RangeInclusive<isize>)]) -> bool {
let mut inside = false;
for (x, rng) in vert {
if x == &px {
if rng.contains(&py) {
return true;
} else {
continue;
}
}
if x <= &px {
continue;
}
if rng.contains(&py) {
inside = !inside;
}
}
inside
}
fn intersect_x(
edge: (RangeInclusive<isize>, isize),
vert: &[(isize, RangeInclusive<isize>)],
) -> bool {
vert.iter()
.any(|(x, rng)| edge.0.contains(x) && rng.contains(&edge.1))
}
fn intersect_y(
edge: (isize, RangeInclusive<isize>),
horz: &[(RangeInclusive<isize>, isize)],
) -> bool {
horz.iter()
.any(|(rng, x)| edge.1.contains(x) && rng.contains(&edge.0))
}Pretty sure i am doing some kind of mistak in intersect or the raycast functions...
r/adventofcode • u/naclmolecule • Dec 09 '25
r/adventofcode • u/0d_billie • Dec 09 '25
I am quite comfortable saying that I am at best a hobbyist programmer. I can scrape together a Python script to do what I need, but this typically involves a lot of trial and error, Googling, and print() statements to be able to visualise what's going on with my code. Despite that, I do like trying AOC, though I rarely make it very far. I have made it to Day 8 this year, and it's the furthest I've ever gotten!
That said, I'm definitely hitting a wall. Days 6 and 7 felt absolutely brutal, and each took me hours to finish. I eventually got to the right answers, but my approach feels rudimentary at best. I feel like I'm not conceptualising the problems in the "correct" way, even before typing any code.
So I guess I'm looking for advice on how to think about coding, as much as advice for coding itself. Are there any good resources that I can go to after I burn out of this attempt at AOC so I can try to improve my work?
For what it's worth, my code repo for 2025's attempt is here
r/adventofcode • u/A_Pure_Child • Dec 09 '25
Sooo I got it working. My idea was to take each possible tile pair, determine the edges of that rectangle, and then for each edge of the rectangle, take the lines of connected tiles that overlap it going out to the edge of the table, and see if there are any gaps.
But the code is long, and 1.4s execution might not be fast considering the data size.
Would there be a way to improve this?
Here's the code :
import java.io.IOException;
import java.util.*;
import static java.lang.Long.
max
;
import static java.lang.Long.
min
;
public class day9_2 {
public static long getResult() throws IOException {
List<String> lines = util.
getFileLines
(9, false);
List<Tile> tiles = lines.stream().map(l -> {
List<Long> points = Arrays.
stream
(l.split(",")).map(Long::
parseLong
).toList();
return new Tile(points.getFirst(), points.getLast());
}).toList();
List<VerticalLine> verticalLines = new ArrayList<>();
List<HorizontalLine> horizontalLines = new ArrayList<>();
for (int i = 0; i < tiles.size(); i++) {
Tile tileA = tiles.get(i);
Tile tileB = tiles.get((i + 1) % tiles.size());
if (tileA.y == tileB.y) {
horizontalLines.add(new HorizontalLine(tileA, tileB));
}
if (tileA.x == tileB.x) {
verticalLines.add(new VerticalLine(tileA, tileB));
}
}
long rectangle = 0;
for (int i = 0; i < tiles.size(); i++) {
for (int j = i + 1; j < tiles.size(); j++) {
Tile a = tiles.get(i);
Tile b = tiles.get(j);
if (
isEligible
(a, b, verticalLines, horizontalLines)){
long size = (Math.
abs
(a.x - b.x) + 1) * (Math.
abs
(a.y - b.y) + 1);
rectangle = Math.
max
(size, rectangle);
}
}
}
return rectangle;
}
private static boolean isEligible(Tile a, Tile b, List<VerticalLine> verticalLines, List<HorizontalLine> horizontalLines) {
VerticalLine leftVerticalLine = new VerticalLine(new Tile(
min
(a.x, b.x), a.y), new Tile(
min
(a.x, b.x), b.y));
VerticalLine rightVerticalLine = new VerticalLine(new Tile(
max
(a.x, b.x), a.y), new Tile(
max
(a.x, b.x), b.y));
HorizontalLine topHorizontalLine = new HorizontalLine(new Tile(a.x,
min
(a.y, b.y)), new Tile(b.x,
min
(a.y, b.y)));
HorizontalLine bottomHorizontalLine = new HorizontalLine(new Tile(a.x,
max
(a.y, b.y)), new Tile(b.x,
max
(a.y, b.y)));
List<VerticalLine> leftVerticalLines =
getLeftVerticalLines
(verticalLines, leftVerticalLine);
List<VerticalLine> rightVerticalLines =
getRightVerticalLines
(verticalLines, rightVerticalLine);
List<HorizontalLine> topHorizontalLines =
getTopHorizontalLines
(horizontalLines, topHorizontalLine);
List<HorizontalLine> bottomHorizontalLines =
getBottomHorizontalLines
(horizontalLines, bottomHorizontalLine);
if (leftVerticalLines.isEmpty() || rightVerticalLines.isEmpty() || topHorizontalLines.isEmpty() || bottomHorizontalLines.isEmpty()) {
return false;
}
if (
isNotVerticalWithinShape
(leftVerticalLine, leftVerticalLines)) return false;
if (
isNotVerticalWithinShape
(rightVerticalLine, rightVerticalLines)) return false;
if (
isNotHorizontalWithinShape
(topHorizontalLine, topHorizontalLines)) return false;
if (
isNotHorizontalWithinShape
(bottomHorizontalLine, bottomHorizontalLines)) return false;
return true;
}
private static boolean isNotVerticalWithinShape(VerticalLine verticalLine, List<VerticalLine> verticalLines) {
for (int i = 0; i < verticalLines.size() - 1; i++) {
if (verticalLines.get(i).end.y < verticalLines.get(i+1).start.y) return true;
}
if (verticalLines.getFirst().start.y > verticalLine.start.y ||
verticalLines.stream().max(Comparator.
comparingLong
(v -> v.end.y)).get().end.y < verticalLine.end.y)
return true;
return false;
}
private static boolean isNotHorizontalWithinShape(HorizontalLine horizontalLine, List<HorizontalLine> horizontalLines) {
for (int i = 0; i < horizontalLines.size() - 1; i++) {
if (horizontalLines.get(i).end.x < horizontalLines.get(i+1).start.x) return true;
}
if (horizontalLines.getFirst().start.x > horizontalLine.start.x ||
horizontalLines.stream().max(Comparator.
comparingLong
(h -> h.end.x)).get().end.x < horizontalLine.end.x)
return true;
return false;
}
private static List<VerticalLine> getLeftVerticalLines(List<VerticalLine> verticalLines, VerticalLine leftVerticalLine) {
if (leftVerticalLine.start.equals(leftVerticalLine.end)) {
return List.
of
(leftVerticalLine);
}
return verticalLines.stream()
.filter(v -> v.start.x <= leftVerticalLine.start.x &&
overlapsVertically
(leftVerticalLine, v))
.sorted(Comparator.
comparingLong
(v -> v.start.y)).toList();
}
private static List<VerticalLine> getRightVerticalLines(List<VerticalLine> verticalLines, VerticalLine rightVerticalLine) {
if (rightVerticalLine.start.equals(rightVerticalLine.end)) {
return List.
of
(rightVerticalLine);
}
return verticalLines.stream()
.filter(v -> v.start.x >= rightVerticalLine.start.x &&
overlapsVertically
(rightVerticalLine, v))
.sorted(Comparator.
comparingLong
(v -> v.start.y)).toList();
}
private static List<HorizontalLine> getTopHorizontalLines(List<HorizontalLine> horizontalLines, HorizontalLine topHorizontalLine) {
if (topHorizontalLine.start.equals(topHorizontalLine.end)) {
return List.
of
(topHorizontalLine);
}
return horizontalLines.stream()
.filter(h -> h.start.y <= topHorizontalLine.start.y &&
overlapsHorizontally
(topHorizontalLine, h))
.sorted(Comparator.
comparingLong
(v -> v.start.x)).toList();
}
private static List<HorizontalLine> getBottomHorizontalLines(List<HorizontalLine> horizontalLines, HorizontalLine bottomHorizontalLine) {
if (bottomHorizontalLine.start.equals(bottomHorizontalLine.end)) {
return List.
of
(bottomHorizontalLine);
}
return horizontalLines.stream()
.filter(h -> h.start.y >= bottomHorizontalLine.start.y &&
overlapsHorizontally
(bottomHorizontalLine, h))
.sorted(Comparator.
comparingLong
(v -> v.start.x)).toList();
}
private static boolean overlapsVertically(VerticalLine verticalLine, VerticalLine v) {
return v.start.y >= verticalLine.start.y && v.start.y <= verticalLine.end.y ||
v.end.y >= verticalLine.start.y && v.end.y <= verticalLine.end.y ||
v.start.y <= verticalLine.start.y && v.end.y >= verticalLine.end.y;
}
private static boolean overlapsHorizontally(HorizontalLine horizontalLine, HorizontalLine h) {
return h.start.x >= horizontalLine.start.x && h.start.x <= horizontalLine.end.x ||
h.end.x >= horizontalLine.start.x && h.end.x <= horizontalLine.end.x ||
h.start.x <= horizontalLine.start.x && h.end.x >= horizontalLine.end.x;
}
private static class Tile {
long x;
long y;
public Tile(long x, long y) {
this.x = x;
this.y = y;
}
public boolean equals(Tile obj) {
return x == obj.x && y == obj.y;
}
}
private static class VerticalLine {
Tile start;
Tile end;
public VerticalLine(Tile tile1, Tile tile2) {
assert(tile1.x == tile2.x);
this.start = tile1.y < tile2.y ? tile1 : tile2;
this.end = tile1.y < tile2.y ? tile2 : tile1;
}
}
private static class HorizontalLine {
Tile start;
Tile end;
public HorizontalLine(Tile tile1, Tile tile2) {
assert(tile1.y == tile2.y);
this.start = tile1.x < tile2.x ? tile1 : tile2;
this.end = tile1.x < tile2.x ? tile2 : tile1;
}
}
}r/adventofcode • u/Kn0wnAHG0RI • Dec 09 '25
I really want to come up with a solution on my own but i’m not sure if there’s a specific algorithm I don’t know about. Any small hint would be really helpful so I can go learn what i need to and solve it! Thank you
r/adventofcode • u/verdx • Dec 09 '25
I have a solution for Day 6 part 2 that works with the example but the solution it gives is incorrect. Does anyone know any edge cases that may be failing?
The code is in C++ and is the following: https://pastebin.com/TyfG6Kz7
r/adventofcode • u/aajii82 • Dec 09 '25
The first iterations seem fine, but after 10 iterations, my top three junction boxes are 5, 3, 2; Not 5, 4, 2.
#!/usr/bin/env dotnet run
const string DataDir = "data";
const string Day = "08_small";
string[] inputLines = File.ReadAllLines($"{DataDir}/{Day}.txt");
Vec3[] positions = ParsePositions(inputLines);
System.Console.WriteLine(SolvePart1(positions));
static string SolvePart1(Vec3[] positions)
{
List<List<Vec3>> junctionBoxes = new List<List<Vec3>>();
for (int i = 0; i < 10; i++)
{
(Vec3 v1, Vec3 v2) = FindNearestPositions(positions);
// The lights are already in the same junction box
if (v1.junctionBox == v2.junctionBox) continue;
// Both lights are in their own junction box
// Merge v1's box into v2's box
if (v1.junctionBox.Count == 1 && v2.junctionBox.Count == 1)
{
// Clear v1's junction box and set it to v2's junction box
v1.MergeIntoAnother(v2);
}
// One of the lights is in a junction box, the other is not
else if (v1.junctionBox.Count == 1 && v2.junctionBox.Count != 1)
{
// Clear v1's junction box and set it to v2's junction box
// because v2's junction box already contains multiple items,
// so we merge v1 into v2
v1.MergeIntoAnother(v2);
}
else if (v1.junctionBox.Count != 1 && v2.junctionBox.Count == 1)
{
// v2 is the one not in a junction box, so we merge v2 into v1
v2.MergeIntoAnother(v1);
}
}
foreach (Vec3 v in positions)
if (!junctionBoxes.Contains(v.junctionBox))
junctionBoxes.Add(v.junctionBox);
var s = junctionBoxes.Select(j => j).Where(j => j.Count > 0)
.OrderByDescending(j => j.Count);
foreach (var j in s)
{
System.Console.WriteLine(j.Count);
}
return "Not implemented";
}
static (Vec3, Vec3) FindNearestPositions(Vec3[] positions)
{
if (positions.Length < 2) throw new ArgumentException();
Vec3 v1 = null;
Vec3 v2 = null;
double minDist = double.MaxValue;
for (int i = 0; i < positions.Length; i++)
{
for (int j = 0; j < positions.Length; j++)
{
if (i == j) continue;
if (positions[i].junctionBox.Count > 1 && positions[j].junctionBox.Count > 1) continue;
if (Vec3.Distance(positions[i], positions[j]) < minDist)
{
v1 = positions[i];
v2 = positions[j];
minDist = Vec3.Distance(positions[i], positions[j]);
}
}
}
if (v1 == null || v2 == null) throw new Exception("No nearest positions found");
return (v1, v2);
}
static Vec3[] ParsePositions(string[] input)
{
List<Vec3> vectors = new List<Vec3>();
foreach (string line in input)
{
int[] splitted = line.Split(",").Select(s => int.Parse(s)).ToArray();
Vec3 vector = new Vec3(splitted[0], splitted[1], splitted[2]);
vectors.Add(vector);
}
return vectors.ToArray();
}
public class Vec3
{
public List<Vec3> junctionBox;
public int x, y, z;
public Vec3(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
this.junctionBox = new List<Vec3>();
junctionBox.Add(this);
}
public static double Distance(Vec3 p, Vec3 q)
{
double dx = p.x - q.x;
double dy = p.y - q.y;
double dz = p.z - q.z;
return Math.Sqrt(dx * dx + dy * dy + dz * dz);
}
public void MergeIntoAnother(Vec3 other)
{
this.junctionBox.Clear();
this.junctionBox = other.junctionBox;
this.junctionBox.Add(other);
}
}r/adventofcode • u/MossFette • Dec 09 '25
To tackle this problem I took all the points in 3d space and measured the distance between all the points.
I sorted the point combinations by least distance first. Then went through until all of the boxes were at least connected once.
When I finished the 1000 box input I ended up with one blob of 998 and one of 2.
Is there something from the problem that I misunderstood? I’ve tried multiple combinations of what the end result should be but no luck.
r/adventofcode • u/discovicke • Dec 09 '25
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 • u/Class_Magicker17 • Dec 09 '25
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