Skip to content

Commit 4d6394e

Browse files
committed
Implement solution to LeetCode problem number 556
Reshape the Matrix, see vJechsmayr#139
1 parent d4bf02f commit 4d6394e

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+
// The original matrix can't fit the requested shape
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)