Technologies:
Tolerim
an hour ago
Rephrase: Locate a two-dimensional array within another two-dimensional array.
let board = [
[ '0', '0', '0', '0' ],
[ '1', '1', '1', '1' ],
[ '2', '3', '3', '4' ]
];
let toFind = [ [ '1', '1' ], [ '4' ] ];
[1,2]
findIndex
, traverses through the board
array, attempting to locate the first element of toFind
array. Upon finding it, the second function, checkMatch
, compares each subsequent element to see if a match is found.
const findIndex = (toFind, board) => {
let results = [];
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[i].length; j++) {
if (board[i][j] == toFind[0][0]) {
if (checkMatch(board, toFind, i, j)) {
console.log("Match Found");
results.push([i, j]);
return results;
}
}
}
}
console.log("Not found");
};
const checkMatch = (board, toFind, row, col) => {
let match = true;
for (let i = row; i < row + toFind.length; i++) {
for (let j = col; j < col + toFind[i - row].length; j++) {
if (toFind[i - row][j - col] != board[i][j]) {
match = false;
}
}
}
console.log(match);
return match;
};
findIndex
function isn't working as efficiently as needed, producing the wrong result [1,0]
. There seems to be an issue with my checkMatch
function, but I'm uncertain about how to correct it.Answers(1)
Tolerim
an hour ago
Verified Answer
The issue with your checkMatch function is that the inner loop should be iterating over the columns of toFind[i], not board[i]. Here's the corrected implementation:
const checkMatch = (board, toFind, row, col) => {
let match = true;
for (let i = row; i < row + toFind.length; i++) {
for (let j = col; j < col + toFind[i - row].length; j++) {
if (toFind[i - row][j - col] !== board[i][j]) {
match = false;
}
}
}
console.log(match)
return match;
};
With this correction, your findIndex function should work correctly and return [1,2] for the example input.