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()
	}
}

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

查看所有标签

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

Ethnography and Virtual Worlds

Ethnography and Virtual Worlds

Tom Boellstorff、Bonnie Nardi、Celia Pearce、T. L. Taylor / Princeton University Press / 2012-9-16 / GBP 21.00

"Ethnography and Virtual Worlds" is the only book of its kind - a concise, comprehensive, and practical guide for students, teachers, designers, and scholars interested in using ethnographic methods t......一起来看看 《Ethnography and Virtual Worlds》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试