pub fn uintLessThan(r: Random, comptime T: type, less_than: T) T r: RandomT: typeless_than: T159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186pub fn uintLessThan(r: Random, comptime T: type, less_than: T) T {
comptime assert(@typeInfo(T).int.signedness == .unsigned);
const bits = @typeInfo(T).int.bits;
assert(0 < less_than);
// adapted from:
// http://www.pcg-random.org/posts/bounded-rands.html
// "Lemire's (with an extra tweak from me)"
var x = r.int(T);
var m = math.mulWide(T, x, less_than);
var l: T = @truncate(m);
if (l < less_than) {
var t = -%less_than;
if (t >= less_than) {
t -= less_than;
if (t >= less_than) {
t %= less_than;
}
}
while (l < t) {
x = r.int(T);
m = math.mulWide(T, x, less_than);
l = @truncate(m);
}
}
return @intCast(m >> bits);
}
Returns an evenly distributed random unsigned integer
0 <= i < less_than. This function assumes that the underlyingfillFnproduces evenly distributed values. Within this assumption, the runtime of this function is exponentially distributed. IffillFnwere backed by a true random generator, the runtime of this function would technically be unbounded. However, iffillFnis backed by any evenly distributed pseudo random number generator, this function is guaranteed to return. If you need deterministic runtime bounds, useuintLessThanBiased.