-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwenty.js
53 lines (41 loc) · 1.12 KB
/
twenty.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { readFile } from 'fs/promises';
let LOOKUP;
// 20
async function init() {
const input = await readFile('twenty.txt', 'utf8');
const [algo, blank, ...grid] = input.split('\n');
calculateLookup(algo);
let image = grid.map((row) => [...row].map(parseFunc));
for (let i = 0; i < 50; i++) {
image = enhance(image, i % 2 === 1);
}
const sum = image.flat().reduce((acc, d) => acc + d, 0);
console.log(sum);
}
function enhance(grid, odd) {
const newGrid = [];
let num = [];
for (let i = -1; i < grid.length + 1; i++) {
newGrid[i + 1] = [];
for (let j = -1; j < grid[0].length + 1; j++) {
num = [];
for (let x = i - 1; x <= i + 1; x++) {
for (let y = j - 1; y <= j + 1; y++) {
num.push(grid?.[x]?.[y] ?? (odd ? 1 : 0));
}
}
const score = parseInt(num.join(''), 2);
const val = LOOKUP[score];
// console.log({ i, j, score, val });
newGrid[i + 1][j + 1] = val;
}
}
return newGrid;
}
function calculateLookup(algo) {
LOOKUP = algo.split('').map(parseFunc);
}
function parseFunc(cell) {
return cell === '#' ? 1 : 0;
}
init();