Skip to content

Feat: Created matrix search function with test cases #1559

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Filter by extension

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)
}
)
})
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

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:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy