@@ -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
1313async 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