JSFiddle - React, Tailwind, and code Playground
by Felis Catus
CSS
body {
font-family: monospace;
}
span.flash {
font-weight: bold;
color: red;
}
JavaScript
let inp = `
7313511551
3724855867
2374331571
4438213437
6511566287
6727245532
3736868662
2348138263
2417483121
8812617112
`;
let data = [[]];
const load = ()=>{
data = inp.split('\n').filter(l=>l.length>0).map(l=>l.trim().split(''));
}
load();
const octopi = ()=>{
let nines = [];
let flashes = 0;
let allflash = -1;
let render = ()=>{
let html = data.reduce(
(table, row)=>`${table}
<div>${row.reduce(
(line, entry)=>`${line}<span class="${entry>9 ? 'flash': ''}">${entry>9 ? '0': entry}</span>`,
'')}<div>`,
'');
document.body.innerHTML = html;
}
render();
let scan = ()=>{
data.forEach((line, row)=>{
line.forEach((entry, column)=>{
entry++;
data[row][column] = entry;
if (entry>9){
nines.push({row, column});
data[row][column] = 10000;
flashes++;
}
});
});
}
let clean = ()=>{
let all = true;
data.forEach((line, row)=>{
line.forEach((entry, column)=>{
if (entry>9)
data[row][column] = 0;
else
all = false;
});
});
return all;
}
let flash = ()=>{
while(nines.length){
let nine = nines.shift();
for (let i=Math.max(nine.row-1, 0); i<=Math.min(nine.row+1, 9); i++){
for (let j=Math.max(nine.column-1, 0); j<=Math.min(nine.column+1, 9); j++){
if (i===nine.row && j===nine.column)
continue;
candidate = data[i][j];
if (candidate>9999)
continue;
candidate++;
if (candidate>9){
candidate = 10000;
flashes++;
nines.push({row:i, column: j});
}
data[i][j] = candidate;
}
}
}
}
let step = (rend)=>{
scan();
flash();
if (rend)
render();
return clean();
}
for (let s = 0; s<1000; s++){
if (step()){
console.log('all flashed at step:', s+1);
render();
break;
};
}
...