Skip to content

Instantly share code, notes, and snippets.

@paul-ridgway
Last active March 25, 2021 19:15
Show Gist options
  • Save paul-ridgway/014d45aa38a19967c5302bd138e726b5 to your computer and use it in GitHub Desktop.
Save paul-ridgway/014d45aa38a19967c5302bd138e726b5 to your computer and use it in GitHub Desktop.
function strokesRequired(picture) {
var strokes = 0;
while (true) {
// Find the next truthy cell and extract x and y
const next = picture.flatMap((row, x) => row.flatMap((char, y) => (char && { char, x, y }))).filter(r => r)[0];
if (!next) { // None left means the picture is filled
break;
}
const remove = [[next.x, next.y]]; // We will remove the current cell after
eliminateNeighbours(picture, [], remove, next.char, next.x, next.y);
remove.forEach(xy => picture[xy[0]][xy[1]] = undefined); // Clean Picture
++strokes;
}
return strokes;
}
function eliminateNeighbours(picture, checked, remove, char, x, y) {
check(picture, checked, remove, char, x + 1, y);
check(picture, checked, remove, char, x - 1, y);
check(picture, checked, remove, char, x, y + 1);
check(picture, checked, remove, char, x, y - 1);
}
function check(picture, checked, remove, char, x, y) {
if (checked.includes(`${x},${y}`)) {
return;
}
checked.push(`${x},${y}`);
if (picture[x] && picture[x][y] === char) {
remove.push([x, y]);
eliminateNeighbours(picture, checked, remove, char, x, y);
}
}
const picture = `
aaaba
aaaba
aaacb
`.split("\n").filter(r => !!r).map(p => p.split(''));
console.log("Result:", strokesRequired(picture));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment