You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
44 lines
1.3 KiB
JavaScript
44 lines
1.3 KiB
JavaScript
const fs = require("fs")
|
|
|
|
const input = fs.readFileSync("input.txt", "utf-8", err => {
|
|
err && console.error(err)
|
|
}).split("\n").filter(line => line).map(line => line.split("").map(digit => parseInt(digit)))
|
|
|
|
let flashed, flashCount = 0
|
|
for (let i = 0;; i++){
|
|
flashed = Array(input.length).fill().map(arr => Array(input.length).fill(false))
|
|
for (let x = 0; x < input.length; x++){
|
|
for (let y = 0; y < input[x].length; y++){
|
|
incAndFlash(x, y)
|
|
}
|
|
}
|
|
flashCount += flashed.flat().filter(flash => flash).length
|
|
if (i === 99){
|
|
console.log(flashCount)
|
|
}
|
|
const all = input.flat()
|
|
if (all.length === all.filter(num => num === 0).length){
|
|
console.log(i + 1)
|
|
break
|
|
}
|
|
}
|
|
|
|
function incAndFlash(x, y){
|
|
if (flashed[y][x])
|
|
return
|
|
input[y][x]++
|
|
if (input[y][x] > 9){
|
|
input[y][x] = 0
|
|
flashed[y][x] = true
|
|
|
|
for (let ny = y - 1; ny <= y + 1; ny++){
|
|
for (let nx = x - 1; nx <= x + 1; nx++){
|
|
if (x === nx && y === ny)
|
|
continue
|
|
if (ny < 0 || nx < 0 || ny > input.length - 1 || nx > input[0].length - 1)
|
|
continue
|
|
incAndFlash(nx, ny)
|
|
}
|
|
}
|
|
}
|
|
} |