Skip to content

Instantly share code, notes, and snippets.

@pengx17
Created December 11, 2021 14:38
Show Gist options
  • Select an option

  • Save pengx17/985094d19633f63c0717418853b35b8c to your computer and use it in GitHub Desktop.

Select an option

Save pengx17/985094d19633f63c0717418853b35b8c to your computer and use it in GitHub Desktop.
let input = `5483143223
2745854711
5264556173
6141336146
6357385478
4167524645
2176841721
6882881134
4846848554
5283751526`;
let w = 10,
h = 10;
let darkest = -Number.MAX_SAFE_INTEGER;
function run() {
let matrix = input
.split("\n")
.filter(Boolean)
.map((row) => row.split("").map((c) => +c));
// padding for one addition row/column with zeros
function padding() {
matrix.unshift(Array(w).fill(darkest));
matrix.push(Array(w).fill(darkest));
matrix = matrix.map((row) => [darkest, ...row, darkest]);
}
padding();
function step(matrix) {
/**
* @type number[][]
*/
let newMatrix = JSON.parse(JSON.stringify(matrix));
for (let y = 1; y < h + 2; y++) {
for (let x = 1; x < w + 2; x++) {
newMatrix[y][x]++;
}
}
let newFlash = false;
do {
newFlash = false;
for (let y = 1; y < h + 2; y++) {
for (let x = 1; x < w + 2; x++) {
if (newMatrix[y][x] === 10) {
newMatrix[y][x]++;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
if (i === 0 && j === 0) {
continue;
}
if (newMatrix[y + i][x + j] <= 9) {
newMatrix[y + i][x + j]++;
if (newMatrix[y + i][x + j] === 10) {
newFlash = true;
}
}
}
}
}
}
}
} while (newFlash);
let counts = 0;
// count how many flashed and reset
for (let y = 1; y < h + 2; y++) {
for (let x = 1; x < w + 2; x++) {
if (newMatrix[y][x] > 9) {
counts++;
newMatrix[y][x] = 0;
}
}
}
return [newMatrix, counts];
}
for (let i = 0; ; i++) {
let [newMatrix, counts] = step(matrix);
totalCounts += counts;
matrix = newMatrix;
if (counts === 100) {
console.log(i);
break;
}
}
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment