File tree Expand file tree Collapse file tree 2 files changed +53
-14
lines changed
Expand file tree Collapse file tree 2 files changed +53
-14
lines changed Original file line number Diff line number Diff line change @@ -4,19 +4,22 @@ import (
44 "math/rand"
55)
66
7- func UniqRands (l int , n int ) []int {
8- set := make (map [int ]struct {})
9- nums := make ([]int , 0 , l )
10- for {
11- num := rand .Intn (n )
12- if _ , ok := set [num ]; ! ok {
13- set [num ] = struct {}{}
14- nums = append (nums , num )
15- }
16- if len (nums ) == l {
17- goto exit
18- }
7+ func UniqRands (quantity int , maxval int ) []int {
8+ if maxval < quantity {
9+ quantity = maxval
1910 }
20- exit:
21- return nums
11+
12+ intSlice := make ([]int , maxval )
13+ for i := 0 ; i < maxval ; i ++ {
14+ intSlice [i ] = i
15+ }
16+
17+ for i := 0 ; i < quantity ; i ++ {
18+ j := rand .Int ()% maxval + i
19+ // swap
20+ intSlice [i ], intSlice [j ] = intSlice [j ], intSlice [i ]
21+ maxval --
22+
23+ }
24+ return intSlice [0 :quantity ]
2225}
Original file line number Diff line number Diff line change 1+ package util
2+
3+ import (
4+ "testing"
5+
6+ "github.com/nsqio/nsq/internal/test"
7+ )
8+
9+ func BenchmarkUniqRands5of5 (b * testing.B ) {
10+ for i := 0 ; i < b .N ; i ++ {
11+ UniqRands (5 , 5 )
12+ }
13+ }
14+ func BenchmarkUniqRands20of20 (b * testing.B ) {
15+ for i := 0 ; i < b .N ; i ++ {
16+ UniqRands (20 , 20 )
17+ }
18+ }
19+
20+ func BenchmarkUniqRands20of50 (b * testing.B ) {
21+ for i := 0 ; i < b .N ; i ++ {
22+ UniqRands (20 , 50 )
23+ }
24+ }
25+
26+ func TestUniqRands (t * testing.T ) {
27+ var x []int
28+ x = UniqRands (3 , 10 )
29+ test .Equal (t , 3 , len (x ))
30+
31+ x = UniqRands (10 , 5 )
32+ test .Equal (t , 5 , len (x ))
33+
34+ x = UniqRands (10 , 20 )
35+ test .Equal (t , 10 , len (x ))
36+ }
You can’t perform that action at this time.
0 commit comments