Skip to content

Commit 2ef5fcd

Browse files
committed
Adds optimized part one
1 parent d7d7ebe commit 2ef5fcd

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

2019/16/part-one-optimized.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Performs much better for larger inputs because:
2+
// - We don't generate long arrays for patterns
3+
const { input } = require('./input');
4+
5+
const base_pattern = [0, 1, 0, -1];
6+
let current = input;
7+
8+
for (let phase = 1; phase <= 100; phase++) {
9+
let new_arr = [];
10+
for (let n = 0; n < current.length; n++) {
11+
let sum = 0;
12+
13+
let index = 0;
14+
let position = n + 1;
15+
for (let i = 0; i < current.length; i++) {
16+
position--;
17+
if (position <= 0) {
18+
position = n + 1;
19+
index = (index + 1) % base_pattern.length;
20+
}
21+
22+
let v = current[i];
23+
let scalar = base_pattern[index];
24+
let new_val = v * scalar;
25+
26+
sum += new_val;
27+
}
28+
29+
let last_digit = Math.abs(sum % 10);
30+
31+
new_arr.push(last_digit);
32+
}
33+
34+
current = new_arr;
35+
}
36+
37+
let first_eight_digits = current.slice(0, 8).join('');
38+
console.log(first_eight_digits);

0 commit comments

Comments
 (0)