1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-11 08:12:26 +08:00

feat: add RandUniqueIntSlice (#108)

This commit is contained in:
Liu Shuang
2023-06-07 11:33:37 +08:00
committed by GitHub
parent a8761eefb0
commit 850800a233
3 changed files with 68 additions and 0 deletions

View File

@@ -114,3 +114,27 @@ func UUIdV4() (string, error) {
return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]), nil
}
// RandUniqueIntSlice generate a slice of random int of length n that do not repeat
func RandUniqueIntSlice(n, min, max int) []int {
if min > max {
return []int{}
}
if n > max-min {
n = max - min
}
nums := make([]int, n)
used := make(map[int]struct{}, n)
for i := 0; i < n; {
r := RandInt(min, max)
if _, use := used[r]; use {
continue
}
used[r] = struct{}{}
nums[i] = r
i++
}
return nums
}