Skip to content

Commit 10b8c67

Browse files
committed
AoC2025: day 8 part 2
1 parent 3e21d94 commit 10b8c67

2 files changed

Lines changed: 42 additions & 4 deletions

File tree

2024-2025/src/2025/day08/day08.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ describe('2025 Day 8', () => {
77
});
88

99
test('Part 2', async () => {
10-
// expect(await part2('testInput1')).toEqual(31);
11-
// expect(await part2('input')).toEqual(29379307);
10+
expect(await part2('testInput1')).toEqual(25272);
11+
expect(await part2('input')).toEqual(9259958565);
1212
});
1313
});

2024-2025/src/2025/day08/day08.ts

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ export async function part1(inputFile: string, isTestInput: boolean = false) {
66
return await day8(inputFile, findCircuits, isTestInput);
77
}
88

9-
export async function part2(inputFile: string, isTestInput: boolean = false) {
10-
return await day8(inputFile, findCircuits, isTestInput);
9+
export async function part2(inputFile: string) {
10+
return await day8(inputFile, findCircuitsPart2);
1111
}
1212

1313
async function day8(inputFile: string, calcFn?: (boxes: Coord3d[], isTestInput: boolean) => number, isTestInput: boolean = false) {
@@ -69,4 +69,42 @@ function findCircuits(boxes: Coord3d[], isTestInput: boolean): number {
6969
sizes.sort((a, b) => b - a);
7070

7171
return sizes[0] * sizes[1] * sizes[2];
72+
}
73+
74+
function findCircuitsPart2(boxes: Coord3d[], _isTestInput: boolean): number {
75+
const n = boxes.length;
76+
77+
const pairs: [number, number, number][] = [];
78+
for (let i = 0; i < n; i++) {
79+
for (let j = i + 1; j < n; j++) {
80+
pairs.push([dist(boxes[i], boxes[j]), i, j]);
81+
}
82+
}
83+
pairs.sort((a, b) => a[0] - b[0]);
84+
85+
const parent = Array.from({length: n}, (_, i) => i);
86+
const size = new Array(n).fill(1);
87+
88+
function find(x: number): number {
89+
while (parent[x] !== x) {
90+
parent[x] = parent[parent[x]];
91+
x = parent[x];
92+
}
93+
return x;
94+
}
95+
96+
let components = n;
97+
for (const [, i, j] of pairs) {
98+
const ri = find(i), rj = find(j);
99+
if (ri === rj) continue;
100+
const [big, small] = size[ri] >= size[rj] ? [ri, rj] : [rj, ri];
101+
parent[small] = big;
102+
size[big] += size[small];
103+
components--;
104+
if (components === 1) {
105+
return boxes[i].x * boxes[j].x;
106+
}
107+
}
108+
109+
return -1;
72110
}

0 commit comments

Comments
 (0)