I'm going to write the understanding of Go from the basics of programming!
package main
import "main/rand" //Same as "fmt"""Surround with
...
}
A package called math/rand for handling random numbers
package main
import "fmt"
import "main/rand"
func main() {
fmt.Println(rand.lntn(10)) //0~Generate 9 random numbers
fmt.Println(rand.lntn(10)) //0~Generate 9 random numbers
}
//console
1
8
By writing "rand.Intn (10)", you can generate random numbers of 10 integers from 0 to 9.
package main
import "fmt"
import "main/rand"
func main() {
for i := 1; i <= 5; i ++ {
fmt.Println(rand.lntn(10))
}
}
//console
[First time] [Second time]
1 1
5 5
3 3
4 4
8 8
Simply calling it like "rand.Intn (10)" The same random number is generated each time it is executed
...
import "main/rand"
import "time" //import time package
func main() {
rand.Seed(time.Now().Unix()) //Code to generate a complete random number
for i := 1; i <= 5; i ++ {
fmt.Println(rand.lntn(10))
}
}
//console
[First time] [Second time]
1 2
5 6
3 1
4 9
8 8
To generate a complete random number I need to add a line that says "rand.Seed (time.Now (). Unix ())" You need to import the "time" package to use this code
Recommended Posts