| 1 |
package random |
| 2 |
|
| 3 |
import "math" |
| 4 |
|
| 5 |
// RandomChoice returns a randomly chosen item from a list of options. You should not store this value, but should use it immediately. |
| 6 |
// |
| 7 |
// This function is not purely for convenience. Signaling to the Antithesis platform that you intend to use a random value in a structured way enables it to provide more interesting choices over time. |
| 8 |
func RandomChoice[T any](things []T) T { |
| 9 |
numThings := len(things) |
| 10 |
if numThings == 0 { |
| 11 |
var nullThing T |
| 12 |
return nullThing |
| 13 |
} |
| 14 |
if numThings == 1 { |
| 15 |
return things[0] |
| 16 |
} |
| 17 |
|
| 18 |
n := uint64(numThings) |
| 19 |
ceiling := (math.MaxUint64 / n) * n |
| 20 |
v := GetRandom() |
| 21 |
for v >= ceiling { |
| 22 |
v = GetRandom() |
| 23 |
} |
| 24 |
return things[v%n] |
| 25 |
} |