Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Search/MatrixSearch.js
Original file line number Diff line number Diff line change
@@ -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 }
51 changes: 51 additions & 0 deletions Search/test/MatrixSearch.test.js
Original file line number Diff line number Diff line change
@@ -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)
}
)
})