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

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






Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.