File tree Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {T } key - The element to be found.
3
+ * @param {T[][] } matrix - The matrix in which the element should be found.
4
+ * @template T
5
+ * @returns {number[] } - An array containing the first found coordinates of the element.
6
+ */
7
+ const MatrixSearch = ( key , matrix ) => {
8
+ for ( let i = 0 ; i < matrix . length ; i ++ ) {
9
+ for ( let j = 0 ; j < matrix [ i ] . length ; j ++ ) {
10
+ if ( matrix [ i ] [ j ] === key ) return [ i , j ] // Found the element, return its coordinates
11
+ }
12
+ }
13
+ return [ - 1 , - 1 ] // Element not found in the matrix
14
+ }
15
+ export { MatrixSearch }
Original file line number Diff line number Diff line change
1
+ import { MatrixSearch } from '../MatrixSearch' // Import the matrix search function
2
+
3
+ describe ( 'MatrixSearchAlgorithm' , ( ) => {
4
+ const searchParam = [
5
+ [
6
+ 5 ,
7
+ [
8
+ [ 1 , 2 , 3 ] ,
9
+ [ 4 , 5 , 6 ] ,
10
+ [ 7 , 8 , 9 ]
11
+ ] ,
12
+ [ 1 , 1 ]
13
+ ] ,
14
+ [
15
+ 5 ,
16
+ [
17
+ [ 1 , 2 , 3 ] ,
18
+ [ 4 , 6 , 7 ] ,
19
+ [ 8 , 9 , 10 ]
20
+ ] ,
21
+ [ - 1 , - 1 ]
22
+ ] ,
23
+ [ 42 , [ [ 42 ] ] , [ 0 , 0 ] ] ,
24
+ [
25
+ 3 ,
26
+ [
27
+ [ 3 , 5 , 7 ] ,
28
+ [ 2 , 4 , 6 ] ,
29
+ [ 1 , 8 , 9 ]
30
+ ] ,
31
+ [ 0 , 0 ]
32
+ ] ,
33
+ [
34
+ 1 ,
35
+ [
36
+ [ 3 , 5 , 7 ] ,
37
+ [ 2 , 4 , 6 ] ,
38
+ [ 1 , 8 , 9 ]
39
+ ] ,
40
+ [ 2 , 0 ]
41
+ ] ,
42
+ [ 5 , [ ] , [ - 1 , - 1 ] ]
43
+ ]
44
+
45
+ test . each ( searchParam ) (
46
+ 'should find the element in the matrix' ,
47
+ ( key , matrix , expected ) => {
48
+ expect ( MatrixSearch ( key , matrix ) ) . toEqual ( expected )
49
+ }
50
+ )
51
+ } )
You can’t perform that action at this time.
0 commit comments