1
1
#!/usr/bin/env node
2
+ /* eslint no-bitwise: 0 */
2
3
const { getInput } = require ( '../utils' ) ;
3
4
4
5
getInput ( )
@@ -9,38 +10,35 @@ getInput()
9
10
const factorB = 48271 ;
10
11
const multipleB = 8 ;
11
12
const divisor = 2147483647 ;
12
- const [ [ , startValueA ] , [ , startValueB ] ] = data . map ( row => row . split ( 'with ' ) ) ;
13
+ const [ [ startValueA ] , [ startValueB ] ] = data . map ( row => / ( \d + ) / g . exec ( row ) ) ;
13
14
14
- const toBinary = value => value . toString ( 2 ) . padStart ( 32 , '0' ) . slice ( 16 , 32 ) ;
15
+ const binaryCompare = ( a , b ) => ( a & 0xFFFF ) === ( b & 0xFFFF ) ;
15
16
16
17
const generate = ( valueA , valueB ) => [
17
18
( valueA * factorA ) % divisor ,
18
19
( valueB * factorB ) % divisor ,
19
20
] ;
20
21
21
22
const part1 = ( ) => {
22
- const pairs = { } ;
23
+ let pairs = 0 ;
23
24
let length = 40000000 ;
24
25
let nextValueA = startValueA ;
25
26
let nextValueB = startValueB ;
26
27
27
28
while ( length ) {
28
29
[ nextValueA , nextValueB ] = generate ( nextValueA , nextValueB ) ;
29
30
30
- const [ binaryA , binaryB ] = [ nextValueA , nextValueB ] . map ( toBinary ) ;
31
-
32
- if ( binaryA === binaryB ) {
33
- pairs [ binaryA ] = pairs [ binaryA ] ? pairs [ binaryA ] += 1 : 1 ;
31
+ if ( binaryCompare ( nextValueA , nextValueB ) ) {
32
+ pairs += 1 ;
34
33
}
35
34
36
35
length -= 1 ;
37
36
}
38
- const numberOfPairs = Object . values ( pairs ) . reduce ( ( sum , value ) => sum + value , 0 ) ;
39
- console . log ( numberOfPairs ) ;
37
+ console . log ( pairs ) ;
40
38
} ;
41
39
42
40
const part2 = ( ) => {
43
- const pairs = { } ;
41
+ let pairs = 0 ;
44
42
const comparablesA = [ ] ;
45
43
const comparablesB = [ ] ;
46
44
let nextValueA = startValueA ;
@@ -57,15 +55,13 @@ getInput()
57
55
}
58
56
59
57
comparablesB . forEach ( ( valueB , index ) => {
60
- const binA = toBinary ( comparablesA [ index ] ) ;
61
- const binB = toBinary ( valueB ) ;
62
- if ( binA === binB ) {
63
- pairs [ binA ] = pairs [ binA ] ? pairs [ binA ] += 1 : 1 ;
58
+ const valueA = comparablesA [ index ] ;
59
+ if ( binaryCompare ( valueA , valueB ) ) {
60
+ pairs += 1 ;
64
61
}
65
62
} ) ;
66
63
67
- const numberOfPairs = Object . values ( pairs ) . reduce ( ( sum , value ) => sum + value , 0 ) ;
68
- console . log ( numberOfPairs ) ;
64
+ console . log ( pairs ) ;
69
65
} ;
70
66
71
67
part1 ( ) ;
0 commit comments