golang 算法-矩阵

栏目: Go · 发布时间: 7年前

内容简介:版权声明:哈哈,一起学习,一起进步 https://blog.csdn.net/qq_36183935/article/details/80785371

版权声明:哈哈,一起学习,一起进步 https://blog.csdn.net/qq_36183935/article/details/80785371

矩阵相乘:

package main

import "fmt"

type SQ struct {
	m,n int
	data [][]int
}
//a的列数和b的行数相等
func mul(a SQ,b SQ) [][]int{
	res := [][]int{}
	for i:=0;i<a.n;i++ {
		t := []int{}
		for j:=0;j<b.m;j++ {
			r := 0
			for k:=0;k<a.m;k++ {
				r += a.data[i][k]*b.data[k][j]
			}
			t = append(t, r)
		}
		res = append(res,t)
	}
	return res
}

func main(){
	a := [][]int{
		{1,2},
		{3,4},
		{5,6},
	}
	b := [][]int{
		{1,2,3},
		{3,4,1},
	}
	A := SQ{
		2,3,
		a,
	}
	B := SQ{
		3,2,
		b,
	}

	res := mul(A,B)
	fmt.Println(res)
}

1、稀疏矩阵的压缩存储

func main(){
	type Res struct{ //压缩后的类型
		i int
		j int
		v int
	}
	var res []Res
	a:=[][]int{    //原矩阵
		{1,0,0,0,0},
		{0,7,0,0,0},
		{0,0,0,0,4},
		{0,3,0,1,0},
		{0,0,8,0,0},
	}
	for i:=0;i<len(a[0]);i++ {
		for j:=0;j<len(a);j++ {
			if a[i][j] != 0 {
				res = append(res,Res{i,j,a[i][j]})
			}
		}
	}
	for _,r := range res {
		fmt.Println(r.i,r.j,r.v)
	}
}
/*结果
0 0 1
1 1 7
2 4 4
3 1 3
3 3 1
4 2 8
*/

2、打印魔方阵

1.首先把第一个数1,放在第一排正中;//估计也是要奇数的原因

2.怎样来确定下一个元素2呢?先找到1的左上方,该地方没有元素,放在左上方就ok了,比如,4,5,6;

3,如果在该元素的左上方已经有元素了,就把下个元素放在自己的下面就ok了;比如3的左上方有1了,就把4放在3下面。

4,重复上面的2,3,;就行了。

func main(){
	N:=3
	var arr [][]int
	for i:=0;i<N;i++ {
		temp := make([]int,N)
		arr = append(arr,temp)
	}

	i:=0
	j:=N/2
	arr[i][j] = 1
	for d:=2;d<=(N*N);d++{//data
		t1:=i
		t2:=j
		i=i-1
		j=j-1
		if i<0 {
			i = N-1
		}
		if j<0 {
			j = N-1
		}
		if arr[i][j] == 0 {
			arr[i][j] = d
			fmt.Println(i,j,arr[i][j])
		}else {
			i=(t1+1)%N
			j=t2
			arr[i][j] = d
			fmt.Println(i,j,arr[i][j])
		}
	}
	for i:=0;i<N;i++ {
		for j:=0;j<N;j++ {
			fmt.Print(arr[i][j])
		}
		fmt.Println()
	}
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

jQuery in Action

jQuery in Action

Bear Bibeault、Yehuda Katz / Manning Publications / 2008-2-17 / USD 39.99

A good web development framework anticipates what you need to do and makes those tasks easier and more efficient; jQuery practically reads your mind. Developers of every stripe-hobbyists and professio......一起来看看 《jQuery in Action》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具