Randomly generating a matrix in Golang

huangapple go评论94阅读模式
英文:

Randomly generating a matrix in Golang

问题

我目前正在编写一个程序,想要随机生成一个矩阵。

目前我正在预设矩阵的值如下:

m1 := [3][3]int{
    [3]int{1, 1, 1},
    [3]int{4, 1, 7},
    [3]int{1, 65, 1},
}

然而,我希望输入的值在1-100的范围内随机生成。

我导入了上述库并尝试使用它。

我已经尝试让它工作,但似乎没有取得任何进展。

m1 := [3][3]int{
    [3]int{rand.Intn(100) + 1, 1, 1},
    [3]int{4, 1, 7},
    [3]int{1, 65, 1},
}

我尝试使用上述解决方案使第一个数字随机生成,但是我得到了以下错误。

cannot use rand.Intn (type func(int) int) as type int in array or slice literal

非常感谢任何帮助。

英文:

I'm currently writing a program and I want to randomly generate a matrix.

Currently I'm pre-setting the values in it as follows:

	m1 := [3][3]int{
	[3]int{1, 1, 1},
	[3]int{4, 1, 7},
	[3]int{1, 65, 1},
}

However I want the values inputted to be randomly generated in a range from 1-100.

import "math/rand"

I am importing the above library and trying to utilise it.

I have attempted to get this working however can't seem to make any headway.

	m1 := [3][3]int{
	[3]int{rand.Intn, 1, 1},
	[3]int{4, 1, 7},
	[3]int{1, 65, 1},
}

I have attempted to complete it with the above solution to make the first number random however I get the following error.

cannot use rand.Intn (type func(int) int) as type int in array or slice literal

Any help greatly appreciated.

答案1

得分: 5

直接的答案是rand.Intn()生成一个介于0和n之间的随机整数,其中n是该方法的一个参数。你得到的错误是编译器抱怨你试图用一个需要两个int并返回一个int的函数来初始化一个int值 - 你试图将一个函数赋给一个int。所以正确的调用应该是像rand.Intn(100)这样的,它会给你一个介于0-100之间的随机数。

然而,为什么要这样做呢?为什么不动态地用随机数初始化你的数组,像这样:

m1 := [3][3]int{}
for i:=0; i<3; i++ {
	for j:=0; j<3; j++ {
		m1[i][j] = rand.Int()
	}
}
英文:

The direct answer is the fact that rand.Intn() generates a random integer between 0 and n, where n is a parameter to this method. The error that you are getting is the compiler complaining that you are trying to initialize an int value with a function that requires two ints and returns one - you are trying to assign a function to an int. So the correct call would be something like rand.Intn(100), which will give you a random number between 0 - 100.

However, why do it this way? Why not dynamically initialize your array with random numbers as:

m1 := [3][3]int{}
for i:=0; i&lt;3; i++ {
	for j:=0; j&lt;3; j++ {
		m1[i][j] = rand.Int()
	}
}

答案2

得分: 0

你的问题的答案已经在上面回答了,这是一个扩展部分。

虽然rand.Int(10)总是给你1,因为它没有种子,
你可以添加这个函数来在每次运行程序时获得随机值,

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func init() {
	rand.Seed(time.Now().UnixNano())
	//我们用当前时间初始化rand变量
	//这样每次运行程序时都会得到不同的输出
}

func main() {
	randMatrix := make([][]int, 3)
	//我们创建了一个长度为3的切片
	//它可以容纳类型为[]int的元素,这些元素的长度可以不同
	for i := 0; i < 3; i++ {
		randMatrix[i] = make([]int, 3)
		//我们创建了一个可以容纳int类型的切片
	}
	generate(randMatrix)
	fmt.Println(randMatrix)
}

func generate(randMatrix [][]int) {
	for i, innerArray := range randMatrix {
		for j := range innerArray {
			randMatrix[i][j] = rand.Intn(100)
			//循环遍历数组的每个元素,并为其赋予一个随机变量
		}
	}
}

这段代码生成一个小于100的随机矩阵,你还可以使用标志(flag)来进行任何未来的用途,并将值泛化,

import "flag"

var outerDim, innerDim, limit *int

func main() {
	outerDim = flag.Int("outerDim", 3, "矩阵的外部维度")
	innerDim = flag.Int("innerDim", 3, "矩阵的内部维度")
	limit = flag.Int("limit", 100, "矩阵值限制为指定值")
	flag.Parse()
	randMatrix := make([][]int, *outerDim)
	for i := 0; i < *outerDim; i++ {
		randMatrix[i] = make([]int, *innerDim)
	}
	generate(randMatrix)
	printMatrix(randMatrix)
}

func generate(randMatrix [][]int) {
	for i, innerArray := range randMatrix {
		for j := range innerArray {
			randMatrix[i][j] = rand.Intn(*limit)
		}
	}
}

func printMatrix(randMatrix [][]int) {
	//循环遍历2D切片并提取1D切片到val
	for _, val := range randMatrix {
		fmt.Println(val) //打印每个切片
	}
}

我们可以修改上面的printMatrix函数,通过循环遍历每个整数,然后使用fmt.Printf()进行格式化,但是当我们不知道限制的长度时,这会使事情变得复杂...

英文:

Answer to your question is answered above, this is an extension,

While rand.Int(10) always gives you 1, as it isn't seeded,
you can add this function to get random values each time you run your program,

package main

import (
    &quot;fmt&quot;
	&quot;math/rand&quot;
	&quot;time&quot;
)

func init() {
	rand.Seed(time.Now().UnixNano())
//we are seeding the rand variable with present time 
//so that we would get different output each time
}

func main() {
	randMatrix := make([][]int, 3) 
// we have created a slice with length 3 
//which can hold type []int, these can be of different length
	for i := 0; i &lt; 3; i++ {
		randMatrix[i] = make([]int, 3) 
// we are creating a slice which can hold type int
	}
	generate(randMatrix)
	fmt.Println(randMatrix)
}

func generate(randMatrix [][]int) {
	for i, innerArray := range randMatrix {
		for j := range innerArray {
			randMatrix[i][j] = rand.Intn(100)
//looping over each element of array and assigning it a random variable
		}
	}
}

This code generates random Matrix, below 100, while you can also use flags for any kind of future use and generalize the values,

import	&quot;flag&quot;

var outerDim, innerDim, limit *int

func main() {
	outerDim = flag.Int(&quot;outerDim&quot;, 3, &quot;Outer dimension of the matrix&quot;)
	innerDim = flag.Int(&quot;innerDim&quot;, 3, &quot;inner dimenstion of the matrix&quot;)
	limit = flag.Int(&quot;limit&quot;, 100, &quot;matrix values are limited specified value&quot;)
	flag.Parse()
	randMatrix := make([][]int, *outerDim)
	for i := 0; i &lt; *outerDim; i++ {
		randMatrix[i] = make([]int, *innerDim)
	}
	generate(randMatrix)
	printMatrix(randMatrix)
}

func generate(randMatrix [][]int) {
	for i, innerArray := range randMatrix {
		for j := range innerArray {
			randMatrix[i][j] = rand.Intn(*limit)
		}
	}
}

func printMatrix(randMatrix [][]int) {
//looping over 2D slice and extracting 1D slice to val
	for _, val := range randMatrix {
		fmt.Println(val)// printing each slice
	}
}

We could modify the printMatrix function above, by looping over each integer and then formatting it well by using fmt.Printf(), but that would complicate things when we don't known the length of the limit...

huangapple
  • 本文由 发表于 2017年5月22日 22:58:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/44116183.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定