Skip to content

Commit 6816e63

Browse files
authored
Merge pull request vJechsmayr#142 from ccjmne/master
Implement solution to LeetCode problem number 556
2 parents 8a25973 + 272a492 commit 6816e63

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Yields all elements of a matrix in a row-traversing order.
3+
* @param {number[][]} matrix
4+
* @yield {number} the next element in the matrix
5+
*/
6+
function* traverse(matrix) {
7+
for (const row of matrix) {
8+
for (const cell of row) {
9+
yield cell;
10+
}
11+
}
12+
}
13+
14+
/**
15+
* Reshapes a matrix into a new one with different size but keep its original data.
16+
*
17+
* Takes a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.
18+
* The reshaped matrix is filled with all the elements of the original matrix in the same row-traversing order as they were.
19+
*
20+
* If the 'reshape' operation with given parameters isn't possible and legal, outputs the original matrix.
21+
*
22+
* @param {number[][]} nums
23+
* @param {number} r
24+
* @param {number} c
25+
* @return {number[][]}
26+
*/
27+
var matrixReshape = function (nums, r, c) {
28+
if (nums.length * nums[0].length !== r * c) {
29+
// Both matrices don't hold the same number of elements.
30+
return nums;
31+
}
32+
33+
const traversal = traverse(nums);
34+
return Array.from({ length: r }, () =>
35+
Array.from({ length: c }, () => traversal.next().value)
36+
);
37+
};

0 commit comments

Comments
 (0)