2023-10-20 13:41:06 +02:00
|
|
|
package lib
|
|
|
|
|
2023-11-03 16:24:18 +01:00
|
|
|
import (
|
|
|
|
"math/rand"
|
|
|
|
)
|
2023-10-20 13:41:06 +02:00
|
|
|
|
|
|
|
// RandomSubsetOfLength: Given an array of nodes generate of random
|
|
|
|
// subset of 'num' length.
|
|
|
|
func RandomSubsetOfLength[V any](vs []V, num int) []V {
|
|
|
|
randomSubset := make([]V, 0)
|
|
|
|
selectedIndices := make(map[int]struct{})
|
|
|
|
|
|
|
|
for i := 0; i < num; {
|
2023-10-20 18:35:02 +02:00
|
|
|
if len(randomSubset) == len(vs) {
|
2023-10-20 13:41:06 +02:00
|
|
|
return randomSubset
|
|
|
|
}
|
|
|
|
|
|
|
|
randomIndex := rand.Intn(len(vs))
|
|
|
|
|
|
|
|
if _, ok := selectedIndices[randomIndex]; !ok {
|
|
|
|
randomSubset = append(randomSubset, vs[randomIndex])
|
2023-11-03 16:24:18 +01:00
|
|
|
selectedIndices[randomIndex] = struct{}{}
|
2023-10-20 13:41:06 +02:00
|
|
|
i++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return randomSubset
|
|
|
|
}
|