1
+ const fs = require ( "fs" )
2
+
3
+ const readData = ( ) => {
4
+ const data = fs
5
+ . readFileSync ( "./input2022-13.txt" , "utf-8" )
6
+ . split ( / \r ? \n \r ? \n / )
7
+ . map ( line => line . split ( / \r ? \n / ) . map ( part => JSON . parse ( part ) ) )
8
+
9
+ return data
10
+ }
11
+
12
+ const main = ( ) => {
13
+ const pairs = readData ( )
14
+
15
+ const compare = ( [ left , right ] ) => {
16
+ if ( [ left , right ] . every ( Number . isInteger ) ) {
17
+ if ( left < right ) return true
18
+ if ( left > right ) return false
19
+ return
20
+ }
21
+
22
+ if ( [ left , right ] . every ( Array . isArray ) ) {
23
+ for ( let i = 0 ; i < Math . min ( left . length , right . length ) ; i ++ ) {
24
+ const res = compare ( [ left [ i ] , right [ i ] ] )
25
+ if ( res != null ) return res
26
+ }
27
+
28
+ return compare ( [ left . length , right . length ] )
29
+ }
30
+
31
+ return compare ( [ [ left ] . flat ( ) , [ right ] . flat ( ) ] )
32
+ }
33
+
34
+ const dividers = [ [ [ 2 ] ] , [ [ 6 ] ] ]
35
+
36
+ const res = [ ...pairs . flat ( ) , ...dividers ]
37
+ . sort ( ( left , right ) => compare ( [ right , left ] ) - compare ( [ left , right ] ) )
38
+ . reduce (
39
+ ( acc , el , index ) => ( dividers . includes ( el ) ? acc * ( index + 1 ) : acc ) ,
40
+ 1
41
+ )
42
+
43
+ console . log ( res )
44
+ }
45
+
46
+ main ( )
0 commit comments