File tree 2 files changed +60
-0
lines changed
2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change @@ -94,6 +94,7 @@ A collection of JavaScript problems and solutions for studying algorithms.
94
94
- [ Diagonal Traverse] ( src/matrix/diagonal-traverse.js )
95
95
- [ Number Of Corner Rectangles] ( src/matrix/number-of-corner-rectangles.js )
96
96
- [ Lonely Pixel I] ( src/matrix/lonely-pixel-i.js )
97
+ - [ Sparse Matrix Multiplication] ( src/matrix/sparse-matrix-multiplication.js )
97
98
98
99
### String
99
100
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Sparse Matrix Multiplication
3
+ *
4
+ * Given two sparse matrices A and B, return the result of AB.
5
+ *
6
+ * You may assume that A's column number is equal to B's row number.
7
+ *
8
+ * Example:
9
+ *
10
+ * Input:
11
+ *
12
+ * A = [
13
+ * [ 1, 0, 0],
14
+ * [-1, 0, 3]
15
+ * ]
16
+ *
17
+ * B = [
18
+ * [ 7, 0, 0 ],
19
+ * [ 0, 0, 0 ],
20
+ * [ 0, 0, 1 ]
21
+ * ]
22
+ *
23
+ * Output:
24
+ *
25
+ * | 1 0 0 | | 7 0 0 | | 7 0 0 |
26
+ * AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
27
+ * | 0 0 1 |
28
+ */
29
+
30
+ /**
31
+ * @param {number[][] } A
32
+ * @param {number[][] } B
33
+ * @return {number[][] }
34
+ */
35
+ const multiply = ( A , B ) => {
36
+ const mA = A . length ;
37
+ const nA = A [ 0 ] . length ;
38
+ const nB = B [ 0 ] . length ;
39
+
40
+ const C = Array ( mA )
41
+ . fill ( )
42
+ . map ( ( ) => Array ( nB ) . fill ( 0 ) ) ;
43
+
44
+ for ( let i = 0 ; i < mA ; i ++ ) {
45
+ for ( let k = 0 ; k < nA ; k ++ ) {
46
+ if ( A [ i ] [ k ] !== 0 ) {
47
+ for ( let j = 0 ; j < nB ; j ++ ) {
48
+ if ( B [ k ] [ j ] != 0 ) {
49
+ C [ i ] [ j ] += A [ i ] [ k ] * B [ k ] [ j ] ;
50
+ }
51
+ }
52
+ }
53
+ }
54
+ }
55
+
56
+ return C ;
57
+ } ;
58
+
59
+ export { multiply } ;
You can’t perform that action at this time.
0 commit comments