diff --git a/Search/MatrixSearch.js b/Search/MatrixSearch.js new file mode 100644 index 0000000000..ce30d265da --- /dev/null +++ b/Search/MatrixSearch.js @@ -0,0 +1,15 @@ +/** + * @param {T} key - The element to be found. + * @param {T[][]} matrix - The matrix in which the element should be found. + * @template T + * @returns {number[]} - An array containing the first found coordinates of the element. + */ +const MatrixSearch = (key, matrix) => { + for (let i = 0; i < matrix.length; i++) { + for (let j = 0; j < matrix[i].length; j++) { + if (matrix[i][j] === key) return [i, j] // Found the element, return its coordinates + } + } + return [-1, -1] // Element not found in the matrix +} +export { MatrixSearch } \ No newline at end of file diff --git a/Search/test/MatrixSearch.test.js b/Search/test/MatrixSearch.test.js new file mode 100644 index 0000000000..eec183c107 --- /dev/null +++ b/Search/test/MatrixSearch.test.js @@ -0,0 +1,51 @@ +import { MatrixSearch } from '../MatrixSearch' // Import the matrix search function + +describe('MatrixSearchAlgorithm', () => { + const searchParam = [ + [ + 5, + [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] + ], + [1, 1] + ], + [ + 5, + [ + [1, 2, 3], + [4, 6, 7], + [8, 9, 10] + ], + [-1, -1] + ], + [42, [[42]], [0, 0]], + [ + 3, + [ + [3, 5, 7], + [2, 4, 6], + [1, 8, 9] + ], + [0, 0] + ], + [ + 1, + [ + [3, 5, 7], + [2, 4, 6], + [1, 8, 9] + ], + [2, 0] + ], + [5, [], [-1, -1]] + ] + + test.each(searchParam)( + 'should find the element in the matrix', + (key, matrix, expected) => { + expect(MatrixSearch(key, matrix)).toEqual(expected) + } + ) +})
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: