curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629efc.md
Today's challenge is inspired by the video game Pong, which was released November 29, 1972.
Given a matrix (array of arrays) that includes the location of the ball (2), and the previous location of the ball (1), return the matrix indices for the next location of the ball.
1 to 2.getNextLocation([[0,0,0,0], [0,0,0,0], [0,1,2,0], [0,0,0,0]]) should return [2, 3].
assert.deepEqual(getNextLocation([[0,0,0,0], [0,0,0,0], [0,1,2,0], [0,0,0,0]]), [2, 3]);
getNextLocation([[0,0,0,0], [0,0,1,0], [0,2,0,0], [0,0,0,0]]) should return [3, 0].
assert.deepEqual(getNextLocation([[0,0,0,0], [0,0,1,0], [0,2,0,0], [0,0,0,0]]), [3, 0]);
getNextLocation([[0,2,0,0], [1,0,0,0], [0,0,0,0], [0,0,0,0]]) should return [1, 2].
assert.deepEqual(getNextLocation([[0,2,0,0], [1,0,0,0], [0,0,0,0], [0,0,0,0]]), [1, 2]);
getNextLocation([[0,0,0,0], [0,0,0,0], [2,0,0,0], [0,1,0,0]]) should return [1, 1].
assert.deepEqual(getNextLocation([[0,0,0,0], [0,0,0,0], [2,0,0,0], [0,1,0,0]]), [1, 1]);
getNextLocation([[0,0,0,0], [0,0,0,0], [0,0,1,0], [0,0,0,2]]) should return [2, 2].
assert.deepEqual(getNextLocation([[0,0,0,0], [0,0,0,0], [0,0,1,0], [0,0,0,2]]), [2, 2]);
function getNextLocation(matrix) {
return matrix;
}
function getNextLocation(matrix) {
let prev = null;
let curr = null;
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[0].length; col++) {
if (matrix[row][col] === 1) prev = [row, col];
if (matrix[row][col] === 2) curr = [row, col];
}
}
const [prevRow, prevCol] = prev;
const [currRow, currCol] = curr;
let dirX = currCol - prevCol;
let dirY = currRow - prevRow;
let nextRow = currRow + dirY;
let nextCol = currCol + dirX;
const maxRow = matrix.length - 1;
const maxCol = matrix[0].length - 1;
if (nextCol < 0 || nextCol > maxCol) dirX *= -1;
if (nextRow < 0 || nextRow > maxRow) dirY *= -1;
nextRow = currRow + dirY;
nextCol = currCol + dirX;
return [nextRow, nextCol];
}