github.com/0chain/gosdk@v1.17.11/core/util/rand.go (about) 1 package util 2 3 import ( 4 "errors" 5 "math/rand" 6 "time" 7 ) 8 9 // MinInt returns the minimum of two integers 10 // - x: first integer 11 // - y: second integer 12 func MinInt(x, y int) int { 13 if x < y { 14 return x 15 } 16 return y 17 } 18 19 // MaxInt returns the maximum of two integers 20 // - x: first integer 21 // - y: second integer 22 func MaxInt(x, y int) int { 23 if x > y { 24 return x 25 } 26 return y 27 } 28 29 // MinInt64 returns the minimum of two int64 30 // - x: first int64 31 // - y: second int64 32 func MinInt64(x, y int64) int64 { 33 if x < y { 34 return x 35 } 36 return y 37 } 38 39 // MaxInt64 returns the maximum of two int64 40 // - x: first int64 41 // - y: second int64 42 func MaxInt64(x, y int64) int64 { 43 if x > y { 44 return x 45 } 46 return y 47 } 48 49 // Shuffle returns a shuffled version of a string slice 50 // - in: input slice 51 func Shuffle(in []string) (shuffle []string) { 52 shuffle = make([]string, len(in)) 53 copy(shuffle, in) 54 var rnd = rand.New(rand.NewSource(time.Now().UnixNano())) 55 rnd.Shuffle(len(in), func(i, j int) { 56 shuffle[i], shuffle[j] = shuffle[j], shuffle[i] 57 }) 58 return 59 } 60 61 // GetRandom returns n random slice from in 62 // If n > len(in), then this will return a shuffled version of in 63 func GetRandom(in []string, n int) []string { 64 n = MinInt(len(in), n) 65 out := make([]string, 0) 66 67 rand.Seed(time.Now().UnixNano()) //nolint 68 perm := rand.Perm(len(in)) 69 for i := 0; i < n; i++ { 70 out = append(out, in[perm[i]]) 71 } 72 return out 73 } 74 75 var ( 76 randGen = rand.New(rand.NewSource(time.Now().UnixNano())) 77 // ErrNoItem there is no item anymore 78 ErrNoItem = errors.New("rand: there is no item anymore") 79 ) 80 81 // Rand a progressive rand 82 type Rand struct { 83 items []int 84 } 85 86 // Next get next random item 87 func (r *Rand) Next() (int, error) { 88 if len(r.items) > 0 { 89 i := randGen.Intn(len(r.items)) 90 91 it := r.items[i] 92 93 copy(r.items[i:], r.items[i+1:]) 94 r.items = r.items[:len(r.items)-1] 95 96 return it, nil 97 } 98 99 return -1, ErrNoItem 100 101 } 102 103 // NewRand create a ProgressiveRand instance 104 func NewRand(max int) Rand { 105 r := Rand{ 106 items: make([]int, max), 107 } 108 109 for i := 0; i < max; i++ { 110 r.items[i] = i 111 } 112 113 return r 114 115 }