Skip to content

Commit 566fde4

Browse files
committed
added matrixReshape
1 parent 463a7ad commit 566fde4

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

matrixReshape.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @param {number[][]} nums
3+
* @param {number} r
4+
* @param {number} c
5+
* @return {number[][]}
6+
*/
7+
var matrixReshape = function(nums, r, c) {
8+
let flat = nums.reduce((acc, i) => {
9+
acc = acc.concat(i);
10+
return acc}, [])
11+
12+
if (r * c !== flat.length){
13+
return nums
14+
}
15+
16+
let results = [],
17+
index = 0;
18+
19+
for (let i = 1; i <= r; i++){
20+
let row = []
21+
for (let j = 1; j <= c; j++){
22+
row.push(flat[index++])
23+
}
24+
results.push(row)
25+
}
26+
27+
return results
28+
};

0 commit comments

Comments
 (0)