Use rand in golang to generate random non-repeating numbers

Release: 2019-12-10 12:01:27
Original
5920 people have browsed it

Use rand in golang to generate random non-repeating numbers

In Golang, there are two packages that provide rand, namely "math/rand" and "crypto/rand", corresponding to two application scenarios.

1. The "math/rand" package implements a pseudo-random number generator. That is, generating integers and floating point types.

2. The "crypto/rand" package implements a more secure random number generator for encryption and decryption.

Use rand in golang to generate random non-repeating numbers:

package test

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

//生成若干个不重复的随机数
func RandomTestBase() {
	//测试5次
	for i := 0; i < 5; i++ {
		nums := generateRandomNumber(10, 30, 10)
		fmt.Println(nums)
	}
}

//生成count个[start,end)结束的不重复的随机数
func generateRandomNumber(start int, end int, count int) []int {
	//范围检查
	if end < start || (end-start) < count {
		return nil
	}

	//存放结果的slice
	nums := make([]int, 0)
	//随机数生成器,加入时间戳保证每次生成的随机数不一样
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for len(nums) < count {
		//生成随机数
		num := r.Intn((end - start)) + start

		//查重
		exist := false
		for _, v := range nums {
			if v == num {
				exist = true
				break
			}
		}

		if !exist {
			nums = append(nums, num)
		}
	}

	return nums
}
Copy after login

Output result:

[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]

Recommended: golang tutorial

The above is the detailed content of Use rand in golang to generate random non-repeating numbers. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!