This is a creation in Article, where the information may have evolved or changed.
Topic
In MATLAB, there are a very useful function called ' reshape ', which can reshape a matrix into a new one with different size But keep its original data.
You ' re given a matrix represented by a two-dimensional array, and the positive integers r and C representing the row Numbe R and column number of the wanted reshaped matrix, respectively.
The reshaped matrix need to is filled with all the elements of the original matrix in the same row-traversing order as the Y were.
If the ' reshape ' operation with given parameters are possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input:
Nums =
[[+],
[3,4]]
R = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of Nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, and the fill it row by row by using the previous list.
Example 2:
Input:
Nums =
[[+],
[3,4]]
R = 2, c = 4
Output:
[[+],
[3,4]]
explanation:
There is no-to-reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
- The height and width of the given matrix is in range [1, 100].
- The given R and C is all positive.
Main topic:
Given a two-dimensional matrix nums, it is transformed into a new matrix of row C columns of R. If the conversion cannot be completed, return to the original matrix.
Attention:
The height and width range of a given matrix [1, 100]
Both R and C are positive numbers.
Thinking of solving problems
- Origin_r * Origin_c matrix reshape for RC, need to satisfy:
Origin_r * Origin_c=rC
- Relationship of element position
If the matrix is expanded horizontally into a one-dimensional array, the number of elements is N=origin_r * Origin_c
In the position of the element in the one-dimensional array I:
Original matrix position [I/origin_c,i%origin_c]
New matrix position [i/c,i%c]
Code
Reshapematrix.go
package _566_Reshape_Matriximport "fmt"func MatrixReshape(nums [][]int, r int, c int) [][]int { var chanInt chan int chanInt = make(chan int) var length int go func(len *int) { for _, v1 := range nums { for _, v := range v1 { (*len)++ fmt.Printf("len1:%+v\n", length) chanInt <- v } } for { chanInt <- 0 } }(&length) var ret [][]int for i := 0; i < r; i++ { var lineRet []int for j := 0; j < c; j++ { v := <- chanInt lineRet = append(lineRet, v) } ret = append(ret, lineRet) } fmt.Printf("len2:%+v\n", length) fmt.Printf("ret:%+v\n", ret) if r * c != length { return nums } return ret}
Test
Reshapematrix_test.go
The package _566_reshape_matriximport "Testing" func Testmatrixreshape (t *testing. T) {input: = [][]int{{1, 2}, {3, 4},} RET: = Matrixreshape (Input, 1, 4) t.logf ("%+v", ret)}