enumValueWithIndex
Returns a random value from an enum, evenly distributed.
An index into an array of all named values is generated using the
specified Index type to determine the return value.
This allows for results to be independent of usize representation.
Prefer enumValue if this isn't important.
See uintLessThan, which this function uses in most cases,
for commentary on the runtime of this function.
Function parameters
Parameters
Fast unbiased random numbers.
Types
- DefaultPrng
- Fast unbiased random numbers.
- DefaultCsprng
- Cryptographically secure random numbers.
Functions in this namespace
Functions
- bytes
- Read random bytes into the specified buffer until full.
- enumValue
- Returns a random value from an enum, evenly distributed.
- enumValueWithIndex
- Returns a random value from an enum, evenly distributed.
- int
- Returns a random int `i` such that `minInt(T) <= i <= maxInt(T)`.
- uintLessThanBiased
- Constant-time implementation off `uintLessThan`.
- uintLessThan
- Returns an evenly distributed random unsigned integer `0 <= i < less_than`.
- uintAtMostBiased
- Constant-time implementation off `uintAtMost`.
- uintAtMost
- Returns an evenly distributed random unsigned integer `0 <= i <= at_most`.
- intRangeLessThanBiased
- Constant-time implementation off `intRangeLessThan`.
- intRangeLessThan
- Returns an evenly distributed random integer `at_least <= i < less_than`.
- intRangeAtMostBiased
- Constant-time implementation off `intRangeAtMostBiased`.
- intRangeAtMost
- Returns an evenly distributed random integer `at_least <= i <= at_most`.
- float
- Return a floating point value evenly distributed in the range [0, 1).
- floatNorm
- Return a floating point value normally distributed with mean = 0, stddev = 1.
- floatExp
- Return an exponentially distributed float with a rate parameter of 1.
- shuffle
- Shuffle a slice into a random order.
- shuffleWithIndex
- Shuffle a slice into a random order, using an index of a
- weightedIndex
- Randomly selects an index into `proportions`, where the likelihood of each
- limitRangeBiased
- Convert a random integer 0 <= random_int <= maxValue(T),
Source
Implementation
pub fn enumValueWithIndex(r: Random, comptime EnumType: type, comptime Index: type) EnumType {
comptime assert(@typeInfo(EnumType) == .@"enum");
// We won't use int -> enum casting because enum elements can have
// arbitrary values. Instead we'll randomly pick one of the type's values.
const values = comptime std.enums.values(EnumType);
comptime assert(values.len > 0); // can't return anything
comptime assert(maxInt(Index) >= values.len - 1); // can't access all values
if (values.len == 1) return values[0];
const index = if (comptime values.len - 1 == maxInt(Index))
r.int(Index)
else
r.uintLessThan(Index, values.len);
const MinInt = MinArrayIndex(Index);
return values[@as(MinInt, @intCast(index))];
}