From 4d6394e7606c8da07260637a4e7ff66e6803e879 Mon Sep 17 00:00:00 2001 From: ccjmne Date: Mon, 7 Oct 2019 23:44:25 +0200 Subject: [PATCH 1/2] Implement solution to LeetCode problem number 556 Reshape the Matrix, see #139 --- .../566_ReshapeTheMatrix_ccjmne.js | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 LeetCode Solutions/566_ReshapeTheMatrix_ccjmne.js diff --git a/LeetCode Solutions/566_ReshapeTheMatrix_ccjmne.js b/LeetCode Solutions/566_ReshapeTheMatrix_ccjmne.js new file mode 100644 index 0000000..c9bfd99 --- /dev/null +++ b/LeetCode Solutions/566_ReshapeTheMatrix_ccjmne.js @@ -0,0 +1,37 @@ +/** + * Yields all elements of a matrix in a row-traversing order. + * @param {number[][]} matrix + * @yield {number} the next element in the matrix + */ +function* traverse(matrix) { + for (const row of matrix) { + for (const cell of row) { + yield cell; + } + } +} + +/** + * Reshapes a matrix into a new one with different size but keep its original data. + * + * 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. + * The reshaped matrix is filled with all the elements of the original matrix in the same row-traversing order as they were. + * + * If the 'reshape' operation with given parameters isn't possible and legal, outputs the original matrix. + * + * @param {number[][]} nums + * @param {number} r + * @param {number} c + * @return {number[][]} + */ +var matrixReshape = function(nums, r, c) { + if (nums.length * nums[0].length > r * c) { + // The original matrix can't fit the requested shape + return nums; + } + + const traversal = traverse(nums); + return Array.from({ length: r }, () => + Array.from({ length: c }, () => traversal.next().value) + ); +}; From 272a49235e01729e41919e4308dfda0910070d61 Mon Sep 17 00:00:00 2001 From: ccjmne Date: Mon, 7 Oct 2019 23:57:31 +0200 Subject: [PATCH 2/2] Disallow generation of sparse matrices After careful reading of the original problem's accompanying examples, it appears sparse matrices are considered *illegal* in this context. --- LeetCode Solutions/566_ReshapeTheMatrix_ccjmne.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/LeetCode Solutions/566_ReshapeTheMatrix_ccjmne.js b/LeetCode Solutions/566_ReshapeTheMatrix_ccjmne.js index c9bfd99..b9cd78d 100644 --- a/LeetCode Solutions/566_ReshapeTheMatrix_ccjmne.js +++ b/LeetCode Solutions/566_ReshapeTheMatrix_ccjmne.js @@ -24,9 +24,9 @@ function* traverse(matrix) { * @param {number} c * @return {number[][]} */ -var matrixReshape = function(nums, r, c) { - if (nums.length * nums[0].length > r * c) { - // The original matrix can't fit the requested shape +var matrixReshape = function (nums, r, c) { + if (nums.length * nums[0].length !== r * c) { + // Both matrices don't hold the same number of elements. return nums; }