@@ -15,7 +15,7 @@ impl Solution for Day08 {
1515 let junction_boxes = self . parse ( input) ;
1616 let mut circuits: Vec < Vec < Point3D > > = Vec :: new ( ) ;
1717
18- for pair in self . closest_limited ( junction_boxes) {
18+ for pair in self . closest_limited ( & junction_boxes) {
1919 let left_circuit = circuits
2020 . iter ( )
2121 . position ( |circuit| circuit. contains ( & pair. 0 ) ) ;
@@ -53,8 +53,43 @@ impl Solution for Day08 {
5353 . to_string ( )
5454 }
5555
56- fn part_two ( & self , _input : & str ) -> String {
57- String :: from ( "0" )
56+ fn part_two ( & self , input : & str ) -> String {
57+ let junction_boxes = self . parse ( input) ;
58+ let mut circuits: Vec < Vec < Point3D > > = Vec :: new ( ) ;
59+
60+ for pair in self . closest_all ( & junction_boxes) {
61+ let left_circuit = circuits
62+ . iter ( )
63+ . position ( |circuit| circuit. contains ( & pair. 0 ) ) ;
64+
65+ let right_circuit = circuits
66+ . iter ( )
67+ . position ( |circuit| circuit. contains ( & pair. 1 ) ) ;
68+
69+ match ( left_circuit, right_circuit) {
70+ ( Some ( left) , Some ( right) ) => {
71+ if left == right {
72+ continue ;
73+ }
74+
75+ for in_circuit in circuits[ right] . clone ( ) {
76+ circuits[ left] . push ( in_circuit) ;
77+ }
78+ circuits. remove ( right) ;
79+ }
80+ ( None , Some ( right) ) => circuits[ right] . push ( pair. 0 ) ,
81+ ( Some ( left) , None ) => circuits[ left] . push ( pair. 1 ) ,
82+ ( None , None ) => {
83+ circuits. push ( vec ! [ pair. 0 , pair. 1 ] ) ;
84+ }
85+ }
86+
87+ if circuits. len ( ) == 1 && circuits. first ( ) . unwrap ( ) . len ( ) == junction_boxes. len ( ) {
88+ return ( pair. 0 . x * pair. 1 . x ) . to_string ( ) ;
89+ }
90+ }
91+
92+ panic ! ( "should not happen" ) ;
5893 }
5994}
6095
@@ -63,11 +98,11 @@ impl Day08 {
6398 input. lines ( ) . map ( |line| line. parse ( ) . unwrap ( ) ) . collect ( )
6499 }
65100
66- fn closest_limited ( & self , boxes : Vec < Point3D > ) -> impl Iterator < Item = Pair > {
101+ fn closest_limited ( & self , boxes : & [ Point3D ] ) -> impl Iterator < Item = Pair > {
67102 self . closest_all ( boxes) . take ( self . connections )
68103 }
69104
70- fn closest_all ( & self , boxes : Vec < Point3D > ) -> impl Iterator < Item = Pair > {
105+ fn closest_all ( & self , boxes : & [ Point3D ] ) -> impl Iterator < Item = Pair > {
71106 let mut calculated: Vec < ( f64 , Pair ) > = Vec :: new ( ) ;
72107 for i in 0 ..boxes. len ( ) {
73108 for j in i + 1 ..boxes. len ( ) {
@@ -129,4 +164,9 @@ mod tests {
129164 fn part_one_example_test ( ) {
130165 assert_eq ! ( "40" , Day08 :: new_for_tests( ) . part_one( EXAMPLE ) ) ;
131166 }
167+
168+ #[ test]
169+ fn part_two_example_test ( ) {
170+ assert_eq ! ( "25272" , Day08 :: new_for_tests( ) . part_two( EXAMPLE ) ) ;
171+ }
132172}
0 commit comments