-
Notifications
You must be signed in to change notification settings - Fork 394
/
rand.go
42 lines (36 loc) · 891 Bytes
/
rand.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Copyright (C) 2023 Storj Labs, Inc.
// See LICENSE for copying information.
package nodeselection
import mathrand "math/rand"
// RandomOrder as an iterator of a pseudo-random permutation set.
type RandomOrder struct {
count uint64
at uint64
prime uint64
len uint64
}
// NewRandomOrder creates new iterator, returns number between [0,n) in pseudo-random order.
func NewRandomOrder(n int) RandomOrder {
if n == 0 {
return RandomOrder{
count: 0,
}
}
return RandomOrder{
count: uint64(n),
at: uint64(mathrand.Intn(n)),
prime: primes[mathrand.Intn(len(primes))],
len: uint64(n),
}
}
// Next generates the next number.
func (r *RandomOrder) Next() bool {
if r.count == 0 {
return false
}
r.at = (r.at + r.prime) % r.len
r.count--
return true
}
// At returns the current number in the permutations.
func (r *RandomOrder) At() uint64 { return r.at }