转置概念:矩阵的行列互换得到的新矩阵称为转置矩阵,而二维数组就是我们通常说的矩阵。
需求:使用Go语言方法实现二维数组(3*3)的矩阵的转置
转置前:
[[ 0, 1, 2],
[ 4, 5, 6],
[ 8, 9, 10]]
转置后
[[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10]]
//使用交换值实现 func (array Num ) Upserver(Aaaay3 [3][3]int) { for i :=0; i<len(Aaaay3);i++{ for j:=0;j<i;j++{ Aaaay3[i][j],Aaaay3[j][i] = Aaaay3[j][i],Aaaay3[i][j] } } fmt.Println(Aaaay3) } //使用临时变量 func (array Num ) Upserver2(Aaaay3 [3][3]int) { temparry :=[3][3]int{} for i :=0; i<len(Aaaay3);i++{ for j:=0;j<i;j++{ //限制j<i 避免多次循环 temparry[i][j]=Aaaay3[i][j] Aaaay3[i][j] =Aaaay3[j][i] Aaaay3[j][i]=temparry[i][j] } } fmt.Println(Aaaay3) }
package main import "fmt" type Num struct { } func (array Num ) Upserver(Aaaay3 [3][3]int) { for i :=0; i<len(Aaaay3);i++{ for j:=0;j<i;j++{ Aaaay3[i][j],Aaaay3[j][i] = Aaaay3[j][i],Aaaay3[i][j] } } fmt.Println(Aaaay3) } func (array Num ) Upserver2(Aaaay3 [3][3]int) { temparry :=[3][3]int{} for i :=0; i<len(Aaaay3);i++{ for j:=0;j<i;j++{ temparry[i][j]=Aaaay3[i][j] Aaaay3[i][j] =Aaaay3[j][i] Aaaay3[j][i]=temparry[i][j] } } fmt.Println(Aaaay3) } func main() { arrinfo :=Num{ } aeey :=[3][3]int{ {0, 1, 2} , /* 第一行索引为 0 */ {4, 5, 6} , /* 第二行索引为 1 */ {8, 9, 10}} fmt.Println(aeey) fmt.Println("****") arrinfo.Upserver(aeey) arrinfo.Upserver2(aeey) }
有疑问加站长微信联系(非本文作者)