1
+ function unique ( networks ) {
2
+ networks = networks . map ( x => x . sort ( ) . join ( "," ) ) ;
3
+ return [ ...new Set ( networks ) ] . map ( x => x . split ( "," ) ) ;
4
+ }
5
+
1
6
function addOneToNetworks ( networks , map ) {
2
- let set = new Set ( ) ;
3
- networks . forEach ( computers => {
7
+ networks = networks . flatMap ( computers => {
4
8
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 ] ) ;
7
11
} ) ;
8
- return set ;
12
+ return unique ( networks ) ;
9
13
}
10
14
11
15
function parse ( input ) {
@@ -20,15 +24,13 @@ function parse(input) {
20
24
21
25
export function part1 ( input ) {
22
26
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 ;
25
30
}
26
31
27
32
export function part2 ( input ) {
28
33
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 ) ;
33
35
return networks [ 0 ] . sort ( ) . join ( "," ) ;
34
36
}
0 commit comments