How to Get Random Permutation of Integers in Golang?


A random permutation of integers is a sequence of integers that has been shuffled randomly. Generating a random permutation is a common task in programming, and Go provides a built-in package for generating random permutations of integers. In this article, we will explore how to generate a random permutation of integers in Go.

Step 1: Create an Integer Slice

The first step to generating a random permutation of integers in Go is to create a slice of integers. You can create a slice of integers using the make function and specifying the length of the slice.

slice := make([]int, length)

In this example, we are creating a slice of integers with a length of length.

Step 2: Populate the Slice with Integers

Once you have created the slice of integers, you can populate it with integers in ascending order using a for loop.

for i := 0; i < length; i++ {
   slice[i] = i
}

In this example, we are using a for loop to populate the slice of integers with the numbers 0 to length-1.

Step 3: Shuffle the Slice

To generate a random permutation of integers in Go, you need to shuffle the slice of integers. You can use the Shuffle function of the math/rand package to shuffle the slice of integers.

rand.Shuffle(length, func(i, j int) {
   slice[i], slice[j] = slice[j], slice[i]
})

In this example, we are using the Shuffle function to shuffle the slice of integers.

Step 4: Use the Random Permutation of Integers

Finally, you can use the generated random permutation of integers in your program as needed. For example, you can print it to the console using the fmt package.

fmt.Println(slice)

By following these simple steps, you can generate a random permutation of integers in Go.

Example

package main

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

func main() {
   length := 10
   slice := make([]int, length)

   for i := 0; i < length; i++ {
      slice[i] = i
   }

   rand.Seed(time.Now().UnixNano())
   rand.Shuffle(length, func(i, j int) {
      slice[i], slice[j] = slice[j], slice[i]
   })

   fmt.Println(slice)
}

Output

[7 9 8 0 2 3 6 4 5 1]

Conclusion

Generating a random permutation of integers in Go is a straightforward process that can be accomplished with just a few lines of code. By following the steps outlined in this article, you can generate a random permutation of any desired length in your Go program. Remember to always seed the random number generator to ensure that the numbers generated are truly random and unpredictable.

Updated on: 08-May-2023

145 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements