Zig 0.17.0-dev (Split by item)

Shortcut keys
?
Show these tips
S
Focus search field
Esc
Clear focus & close tips
U
Jump to source code
↑
Move up in search results
↓
Move down in search results
↵
Go to active search result
This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig standard library. Public Function

uintLessThan

Public Function
std.Random.uintLessThan
pub fn uintLessThan(r: Random, comptime T: type, less_than: T) T

Returns an evenly distributed random unsigned integer 0 <= i < less_than. This function assumes that the underlying fillFn produces evenly distributed values. Within this assumption, the runtime of this function is exponentially distributed. If fillFn were backed by a true random generator, the runtime of this function would technically be unbounded. However, if fillFn is backed by any evenly distributed pseudo random number generator, this function is guaranteed to return. If you need deterministic runtime bounds, use uintLessThanBiased.

Params

  • r: Random
  • T: type
  • less_than: T

File

Random.zig:159
159
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
186
pub 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);
}