forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
sampler.go
49 lines (43 loc) · 1.28 KB
/
sampler.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
43
44
45
46
47
48
49
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package bootstrapper
import (
"github.com/MetalBlockchain/metalgo/utils/math"
"github.com/MetalBlockchain/metalgo/utils/sampler"
"github.com/MetalBlockchain/metalgo/utils/set"
)
// Sample keys from [elements] uniformly by weight without replacement. The
// returned set will have size less than or equal to [maxSize]. This function
// will error if the sum of all weights overflows.
func Sample[T comparable](elements map[T]uint64, maxSize int) (set.Set[T], error) {
var (
keys = make([]T, len(elements))
weights = make([]uint64, len(elements))
totalWeight uint64
err error
)
i := 0
for key, weight := range elements {
keys[i] = key
weights[i] = weight
totalWeight, err = math.Add64(totalWeight, weight)
if err != nil {
return nil, err
}
i++
}
sampler := sampler.NewWeightedWithoutReplacement()
if err := sampler.Initialize(weights); err != nil {
return nil, err
}
maxSize = int(min(uint64(maxSize), totalWeight))
indices, err := sampler.Sample(maxSize)
if err != nil {
return nil, err
}
sampledElements := set.NewSet[T](maxSize)
for _, index := range indices {
sampledElements.Add(keys[index])
}
return sampledElements, nil
}