Skip to content

Commit 40cecfc

Browse files
committed
Refactoring day15
1 parent 35c772e commit 40cecfc

File tree

1 file changed

+12
-16
lines changed

1 file changed

+12
-16
lines changed

day15/index.js

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#!/usr/bin/env node
2+
/* eslint no-bitwise: 0 */
23
const { getInput } = require('../utils');
34

45
getInput()
@@ -9,38 +10,35 @@ getInput()
910
const factorB = 48271;
1011
const multipleB = 8;
1112
const divisor = 2147483647;
12-
const [[, startValueA], [, startValueB]] = data.map(row => row.split('with '));
13+
const [[startValueA], [startValueB]] = data.map(row => /(\d+)/g.exec(row));
1314

14-
const toBinary = value => value.toString(2).padStart(32, '0').slice(16, 32);
15+
const binaryCompare = (a, b) => (a & 0xFFFF) === (b & 0xFFFF);
1516

1617
const generate = (valueA, valueB) => [
1718
(valueA * factorA) % divisor,
1819
(valueB * factorB) % divisor,
1920
];
2021

2122
const part1 = () => {
22-
const pairs = {};
23+
let pairs = 0;
2324
let length = 40000000;
2425
let nextValueA = startValueA;
2526
let nextValueB = startValueB;
2627

2728
while (length) {
2829
[nextValueA, nextValueB] = generate(nextValueA, nextValueB);
2930

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;
3433
}
3534

3635
length -= 1;
3736
}
38-
const numberOfPairs = Object.values(pairs).reduce((sum, value) => sum + value, 0);
39-
console.log(numberOfPairs);
37+
console.log(pairs);
4038
};
4139

4240
const part2 = () => {
43-
const pairs = {};
41+
let pairs = 0;
4442
const comparablesA = [];
4543
const comparablesB = [];
4644
let nextValueA = startValueA;
@@ -57,15 +55,13 @@ getInput()
5755
}
5856

5957
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;
6461
}
6562
});
6663

67-
const numberOfPairs = Object.values(pairs).reduce((sum, value) => sum + value, 0);
68-
console.log(numberOfPairs);
64+
console.log(pairs);
6965
};
7066

7167
part1();

0 commit comments

Comments
 (0)