Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Loop in loop solution in Clear category for [old] Moore Neighbourhood by Kolya-YA
const countNeighbours = (data, row, col) => {
let res = -data[row][col]
for (let i = row - 1; i < row + 2; i++) {
for (let j = col - 1; j < col + 2; j++) {
if (data[i] && data[i][j]) res += data[i][j];
}
}
return res;
}
var assert = require('assert');
if (!global.is_checking) {
assert.equal(countNeighbours([[1, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 1],
[1, 0, 0, 0, 0],
[0, 0, 1, 0, 0]], 1, 2), 3, "1st example");
assert.equal(countNeighbours([[1, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 1],
[1, 0, 0, 0, 0],
[0, 0, 1, 0, 0]], 0, 0), 1, "2nd example");
assert.equal(countNeighbours([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]], 0, 2), 3, "Dense corner");
assert.equal(countNeighbours([[0, 0, 0],
[0, 1, 0],
[0, 0, 0]], 1, 1), 0, "Single");
console.log("Coding complete? Click 'Check' to review your tests and earn cool rewards!");
}
March 4, 2019
Comments: