Golang programming implements the method of generating n from a to b without repeating random Numbers

  • 2020-06-01 10:01:59
  • OfStack

This article illustrates the programming implementation of Golang to generate n random Numbers from a to b without repeating random Numbers. I will share it with you for your reference as follows:

The code is simple:

package test
import (
    "fmt"
    "math/rand"
    "time"
)
// Generate several random Numbers that do not repeat
func RandomTestBase() {
    // test 5 time
    for i := 0; i < 5; i++ {
        nums := generateRandomNumber(10, 30, 10)
        fmt.Println(nums)
    }
}
// generate count a [start,end) A random number that ends without repeating
func generateRandomNumber(start int, end int, count int) []int {
    // Scope of inspection
    if end < start || (end-start) < count {
        return nil
    }
    // Store the results slice
    nums := make([]int, 0)
    // Random number generator, add a timestamp to ensure that the random number generated each time is not 1 sample
    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    for len(nums) < count {
        // Generate random number
        num := r.Intn((end - start)) + start
        // rechecking
        exist := false
        for _, v := range nums {
            if v == num {
                exist = true
                break
            }
        }
        if !exist {
            nums = append(nums, num)
        }
    }
    return nums
}

Output results:


[12 20 18 19 21 28 15 13 11 10]
[28 15 12 10 20 18 16 24 27 17]
[25 28 29 19 21 12 16 13 11 15]
[27 20 19 23 18 13 21 24 12 26]
[19 10 27 18 28 12 22 14 16 26]

I hope this article has been helpful to you in the programming of Go language.


Related articles: