Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 32c063d

Browse files
author
Sandy
authored
Merge pull request #186 from openset/develop
Add: Reshape the Matrix
2 parents 1e7a148 + 01684f0 commit 32c063d

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,23 @@
11
package reshape_the_matrix
2+
3+
func matrixReshape(nums [][]int, r int, c int) [][]int {
4+
m, n := len(nums), len(nums[0])
5+
if m*n != r*c {
6+
return nums
7+
}
8+
ans := make([][]int, r)
9+
for i := 0; i < r; i++ {
10+
ans[i] = make([]int, c)
11+
}
12+
i, j := 0, 0
13+
for _, row := range nums {
14+
for _, v := range row {
15+
ans[i][j] = v
16+
if j++; j == c {
17+
i++
18+
j = 0
19+
}
20+
}
21+
}
22+
return ans
23+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,48 @@
11
package reshape_the_matrix
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
nums [][]int
10+
r int
11+
c int
12+
expected [][]int
13+
}
14+
15+
func TestMatrixReshape(t *testing.T) {
16+
tests := [...]caseType{
17+
{
18+
nums: [][]int{
19+
{1, 2},
20+
{3, 4},
21+
},
22+
r: 1,
23+
c: 4,
24+
expected: [][]int{
25+
{1, 2, 3, 4},
26+
},
27+
},
28+
{
29+
nums: [][]int{
30+
{1, 2},
31+
{3, 4},
32+
},
33+
r: 2,
34+
c: 4,
35+
expected: [][]int{
36+
{1, 2},
37+
{3, 4},
38+
},
39+
},
40+
}
41+
for _, tc := range tests {
42+
output := matrixReshape(tc.nums, tc.r, tc.c)
43+
if !reflect.DeepEqual(output, tc.expected) {
44+
t.Fatalf("input: %v, output: %v, expected: %v", tc.nums, output, tc.expected)
45+
46+
}
47+
}
48+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /