How to Generate a Array of Unique Random Numbers in Golang?


In many programming applications, we need to generate an array of unique random numbers. This can be useful for tasks such as creating unique IDs or selecting random items from a list without repetition. In this article, we will explore how to generate an array of unique random numbers in Golang.

Using The math/rand Package

The math/rand package in Golang provides a simple way to generate random numbers. However, by default, the random numbers generated by the math/rand package are not guaranteed to be unique. To generate an array of unique random numbers, we need to add some extra logic.

Example

Here's a simple approach to generate an array of unique random numbers using the math/rand package −

package main

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

func generateUniqueRandomNumbers(n, max int) []int {
   rand.Seed(time.Now().UnixNano())
   set := make(map[int]bool)
   var result []int
   for len(set) < n {
      value := rand.Intn(max)
      if !set[value] {
         set[value] = true
         result = append(result, value)
      }
   }
   return result
}

func main() {
    uniqueRandomNumbers := generateUniqueRandomNumbers(10, 100)
    fmt.Println(uniqueRandomNumbers)
}

Output

[93 14 48 92 41 74 7 27 80 34]

In this code, we define a function generateUniqueRandomNumbers that takes two arguments, n and max, where n is the number of unique random numbers we want to generate and max is the maximum value of the random numbers.

The function first seeds the random number generator using the current time. We then create a set to keep track of the unique values we generate and an empty slice to hold the final result.

We then enter a loop that generates random numbers and adds them to the set until the set contains n unique values. To ensure that the random numbers are unique, we check if the generated value is already in the set. If not, we add it to the set and append it to the result slice.

Finally, we return the result slice containing n unique random numbers.

Conclusion

Generating an array of unique random numbers in Golang can be achieved using the math/rand package. By adding some extra logic to check for uniqueness, we can generate an array of unique random numbers for various use cases.

Updated on: 05-May-2023

774 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements