-
-
Save Mellen/0a194f08102d99563a1b3cdd3c406f41 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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