Files
container/sampler/weighted_without_replacement_generic.go
zeekayandHanzo Dev adf4508709 Go 1.27.1, and the code it can say more simply
Modules declare go 1.27.1 and the build images follow. go fix applied the
modernizers: any, WaitGroup.Go, range over int, and a promoted-field key in
a struct literal. omitzero is not applied, since it changes what the JSON
says.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-16 19:46:08 -07:00

43 lines
873 B
Go

// Copyright (C) 2019-2025, Lux Industries, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package sampler
import "github.com/luxfi/math"
type weightedWithoutReplacementGeneric struct {
u Uniform
w Weighted
}
func (s *weightedWithoutReplacementGeneric) Initialize(weights []uint64) error {
totalWeight := uint64(0)
for _, weight := range weights {
newWeight, err := math.Add64(totalWeight, weight)
if err != nil {
return err
}
totalWeight = newWeight
}
s.u.Initialize(totalWeight)
return s.w.Initialize(weights)
}
func (s *weightedWithoutReplacementGeneric) Sample(count int) ([]int, bool) {
s.u.Reset()
indices := make([]int, count)
for i := range count {
weight, ok := s.u.Next()
if !ok {
return nil, false
}
indices[i], ok = s.w.Sample(weight)
if !ok {
return nil, false
}
}
return indices, true
}