Source file src/cmd/compile/internal/contraire/alt.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package contraire
     6  
     7  import "math/rand"
     8  
     9  // chooseUniform selects an alternative from alts uniformly.
    10  func chooseUniform[T any](alts []T) T {
    11  	return alts[rand.Intn(len(alts))]
    12  }
    13  
    14  // alt is an alternative in a cumulative distribution function (CDF).
    15  type alt[T any] struct {
    16  	p int // 0 <= p <= 100
    17  	f func() T
    18  }
    19  
    20  const checkCDF = false
    21  
    22  // chooseCDF selects a single alternative by observing a uniform random variable
    23  // and comparing it to the CDF of the given alternatives.
    24  func chooseCDF[T any](alts ...alt[T]) T {
    25  	if checkCDF {
    26  		verify(alts)
    27  	}
    28  	sum := 0
    29  	choice := rand.Intn(100)
    30  	for _, alt := range alts {
    31  		sum += alt.p
    32  		if choice < sum {
    33  			return alt.f()
    34  		}
    35  	}
    36  	panic("alternative probabilities sum to less than 100")
    37  }
    38  
    39  // verify checks that the given alternatives are suitable for chooseCDF.
    40  func verify[T any](alts []alt[T]) {
    41  	sum := 0
    42  	for _, alt := range alts {
    43  		sum += alt.p
    44  	}
    45  	if sum != 100 {
    46  		panic("alternative probabilities must sum to 100")
    47  	}
    48  }
    49  
    50  // oneToN picks a number uniformly on [1, n].
    51  func oneToN(n int) int {
    52  	return rand.Intn(n) + 1
    53  }
    54  

View as plain text