-
-
Save Mellen/385affbe222d0d422487e1604d926c22 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(inp) | |
{ | |
function getNeighbours(x,y,width) | |
{ | |
let deltas = [ | |
[-1,-1], | |
[-1,0], | |
[-1,1], | |
[0,-1], | |
[0,1], | |
[1,-1], | |
[1,0], | |
[1,1] | |
]; | |
let neighbours = []; | |
for(let delta of deltas) | |
{ | |
let [xd, yd] = delta; | |
let nx = xd+x; | |
let ny = yd+y; | |
if(nx < 0 || nx >= width || ny < 0 || ny >= width) | |
{ | |
continue; | |
} | |
neighbours.push([nx, ny]); | |
} | |
return neighbours; | |
} | |
function updateNeightbours(octopusses, currentIndex, alreadyFlashed, width, flashValue) | |
{ | |
let flashcount = 0; | |
let x = currentIndex%width; | |
let y = Math.floor(currentIndex/width); | |
let neighbours = getNeighbours(x,y,width); | |
for(let neigh of neighbours) | |
{ | |
let [nx, ny] = neigh; | |
let ni = nx + ny*width; | |
if(!alreadyFlashed.includes(ni)) | |
{ | |
octopusses[ni]++; | |
if(octopusses[ni] > flashValue) | |
{ | |
alreadyFlashed.push(ni); | |
flashcount++; | |
octopusses[ni] = 0; | |
flashcount += updateNeightbours(octopusses, ni, alreadyFlashed, width, flashValue); | |
} | |
} | |
} | |
return flashcount; | |
} | |
const width = 10; | |
const flashValue = 9; | |
let octopusses = inp.split('\n').filter(line=>line!='').map(line => line.split('').map(n => parseInt(n, 10))).flat(); | |
let init = ''; | |
let oi = 0; | |
for(let octo of octopusses) | |
{ | |
init += octo.toString(); | |
if(oi == 9) | |
{ | |
init += '\n'; | |
oi = 0; | |
} | |
else | |
{ | |
oi++; | |
} | |
} | |
console.log(init); | |
let flashcount = 0; | |
for(let _ = 0; _ < 100; _++) | |
{ | |
let alreadyflashed = []; | |
for(let octoIndex = 0; octoIndex < octopusses.length; octoIndex++) | |
{ | |
if(alreadyflashed.includes(octoIndex)) | |
{ | |
continue; | |
} | |
octopusses[octoIndex]++ | |
if(octopusses[octoIndex] > flashValue) | |
{ | |
octopusses[octoIndex] = 0; | |
alreadyflashed.push(octoIndex); | |
flashcount++; | |
flashcount += updateNeightbours(octopusses, octoIndex, alreadyflashed, width, flashValue); | |
} | |
} | |
let s = ''; | |
let ri = 0 | |
for(let octo of octopusses) | |
{ | |
s += octo.toString(); | |
if(ri == 9) | |
{ | |
s += '\n'; | |
ri = 0; | |
} | |
else | |
{ | |
ri++; | |
} | |
} | |
console.log(s); | |
} | |
return flashcount; | |
})(document.querySelector('pre').textContent); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment