curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d5.md
In day four of Space Week, you are given a matrix of numbers (an array of arrays), representing potential landing spots for your rover. Find the safest landing spot based on the following rules:
0-9, inclusive.0 represents a potential landing spot.0 is too dangerous to land. The higher the number, the more dangerous.0 cell whose surrounding cells (up to 4 neighbors, ignore diagonals) have the lowest total danger.For instance, given:
[
[1, 0],
[2, 0]
]
Return [0, 1], the indices for the 0 in the first array.
findLandingSpot([[1, 0], [2, 0]]) should return [0, 1].
assert.deepEqual(findLandingSpot([[1, 0], [2, 0]]), [0, 1]);
findLandingSpot([[9, 0, 3], [7, 0, 4], [8, 0, 5]]) should return [1, 1].
assert.deepEqual(findLandingSpot([[9, 0, 3], [7, 0, 4], [8, 0, 5]]), [1, 1]);
findLandingSpot([[1, 2, 1], [0, 0, 2], [3, 0, 0]]) should return [2, 2].
assert.deepEqual(findLandingSpot([[1, 2, 1], [0, 0, 2], [3, 0, 0]]), [2, 2]);
findLandingSpot([[9, 6, 0, 8], [7, 1, 1, 0], [3, 0, 3, 9], [8, 6, 0, 9]]) should return [2, 1].
assert.deepEqual(findLandingSpot([[9, 6, 0, 8], [7, 1, 1, 0], [3, 0, 3, 9], [8, 6, 0, 9]]), [2, 1]);
function findLandingSpot(matrix) {
return matrix;
}
function findLandingSpot(matrix) {
let bestSpot = null;
let lowestNeighborSum = Infinity;
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] === 0) {
let currentNeighborSum = 0;
if (i > 0) currentNeighborSum += matrix[i - 1][j];
if (j < matrix[i].length - 1) currentNeighborSum += matrix[i][j + 1];
if (i < matrix.length - 1) currentNeighborSum += matrix[i + 1][j];
if (j > 0) currentNeighborSum += matrix[i][j - 1];
if (currentNeighborSum < lowestNeighborSum) {
lowestNeighborSum = currentNeighborSum;
bestSpot = [i, j];
}
}
}
}
return bestSpot;
}