Write a function that takes 2 inputs:
- a matrix, for example 2-dimensional array, and
- indices, for example [row, col]
This function should return the sum of all the second input's neighbors (up, down, left, right, diagonals).
Below is my solution. Just wanted to know if there is a better way to solve this problem. And also wanted to know if I am covering all the edge cases.
function findingNeibors(myArray, i,j) {
let rowLimit = myArray.length-1;
let columnLimit= myArray[0].length-1;
let sum = 0;
if(i<0 || j< 0) {
console.log("invalid Index")
return
};
if(i>rowLimit || j> columnLimit){
console.log("You are Out Of Bound");
return;
}
for(let x = Math.max(0,i-1); x<=Math.min(i+1,rowLimit); x++){
for(let y = Math.max(0,j-1); y<=Math.min(j+1,columnLimit); y++){
if(x!==i || y!==j){
console.log(myArray[x][y]);
sum+=myArray[x][y];
}
}
}
return sum;
}
let input = [
[0,1,2,3,4],
[1,2,3,4,5],
[2,3,4,5,6]
]
findingNeibors(input,0,0);
findingNeibors(input,2,2,0);
findingNeibors(input,-1,3);
findingNeibors(input,3,4);
```