From fb7da367def4b8aaa47dea3c806d455df0443392 Mon Sep 17 00:00:00 2001 From: shahayush480 Date: Sat, 21 Oct 2023 09:00:32 +0530 Subject: [PATCH] Feat: Created matrix search function with test cases --- Search/MatrixSearch.js | 15 ++++++++++ Search/test/MatrixSearch.test.js | 51 ++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 Search/MatrixSearch.js create mode 100644 Search/test/MatrixSearch.test.js 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) + } + ) +})