1+ function unique ( networks ) {
2+ networks = networks . map ( x => x . sort ( ) . join ( "," ) ) ;
3+ return [ ...new Set ( networks ) ] . map ( x => x . split ( "," ) ) ;
4+ }
5+
16function addOneToNetworks ( networks , map ) {
2- let set = new Set ( ) ;
3- networks . forEach ( computers => {
7+ networks = networks . flatMap ( computers => {
48 let candidates = computers . map ( c => map . get ( c ) ) ;
5- let result = candidates . reduce ( ( a , b ) => a . intersection ( b ) ) ;
6- result . forEach ( x => set . add ( [ ...computers , x ] . sort ( ) . join ( "," ) ) ) ;
9+ let result = [ ... candidates . reduce ( ( a , b ) => a . intersection ( b ) ) ] ;
10+ return result . map ( x => [ ...computers , x ] ) ;
711 } ) ;
8- return set ;
12+ return unique ( networks ) ;
913}
1014
1115function parse ( input ) {
@@ -20,15 +24,13 @@ function parse(input) {
2024
2125export function part1 ( input ) {
2226 let { networks, map } = parse ( input ) ;
23- let set = addOneToNetworks ( networks , map ) ;
24- return [ ...set ] . filter ( x => x . match ( / ( ^ t | , t ) / ) ) . length ;
27+ networks = addOneToNetworks ( networks , map ) ;
28+ networks = networks . filter ( c => c . some ( x => x . startsWith ( "t" ) ) ) ;
29+ return networks . length ;
2530}
2631
2732export function part2 ( input ) {
2833 let { networks, map } = parse ( input ) ;
29- while ( networks . length > 1 ) {
30- let next = addOneToNetworks ( networks , map ) ;
31- networks = [ ...next ] . map ( x => x . split ( "," ) ) ;
32- }
34+ while ( networks . length > 1 ) networks = addOneToNetworks ( networks , map ) ;
3335 return networks [ 0 ] . sort ( ) . join ( "," ) ;
3436}
0 commit comments