Go language-rand package

rand package

I'm going to write the understanding of Go from the basics of programming!

Random display of processing results

package main
import "main/rand"  //Same as "fmt"""Surround with
...
}

A package called math/rand for handling random numbers

Random number generation

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.

Notes on random numbers

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

Generate a complete random number

...
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

Go language-rand package
Go language-standard package
[Go] Execution / build / package test
Go Language-Basic ❶
Go language-fmt.Scan
Go language-address
Go Language-Functions
Go language-pointer
Go Language-Basic ❷
GO Chokisomemo 1
Go language-iteration
Load a package created locally with Go Module