Skip to content

Instantly share code, notes, and snippets.

@Mellen
Created December 11, 2021 11:06
Show Gist options
  • Select an option

  • Save Mellen/0a194f08102d99563a1b3cdd3c406f41 to your computer and use it in GitHub Desktop.

Select an option

Save Mellen/0a194f08102d99563a1b3cdd3c406f41 to your computer and use it in GitHub Desktop.
(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 step = 0;
let flashcount = 0;
while(flashcount < 100)
{
flashcount = 0;
step++;
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);
}
}
}
return step;
})(document.querySelector('pre').textContent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment