Home »
Golang »
Golang Programs
Golang program to generate the slice of random numbers
Here, we are going to learn how to generate the slice of random numbers in Golang (Go Language)?
Submitted by Nidhi, on April 29, 2021 [Last updated : March 05, 2023]
How to generate the slice of random numbers in Golang?
Problem Solution:
Here, we will generate the slice of random numbers using the rand.Perm() number. The rand.Perm() function returns the specified number of random numbers between 0-N. Here, N is the specified number in the rand.Perm() function.
Program/Source Code:
The source code to generate the slice of random numbers is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
Golang code to generate the slice of random numbers
// Golang program to generate the
// slice of random numbers
package main
import "math/rand"
import "fmt"
//Entry point for the program
func main() {
slice := rand.Perm(10)
fmt.Println("Slice of 10 random numbers:")
for i := 0; i < 10; i++ {
fmt.Printf("%d ", slice[i])
}
fmt.Println()
}
Output:
Slice of 10 random numbers:
9 4 2 6 8 0 3 1 7 5
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the required packages to predefined functions.
In the main() function, we used the rand.Perm() function to generate the slice of random numbers. Here, we generated 10 random numbers between 0-10. Because, the rand.Perm() function generates a slice of N numbers between 0-N.
Golang math/rand Package Programs »