Zig 0.17.0-dev (Split by item)

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 library itself.

shuffleWithIndex

Shuffle a slice into a random order, using an index of a specified type to maintain distribution across targets. Asserts the index type can represent buf.len.

Indexes into the slice are generated using the specified Index type, which determines distribution properties. This allows for results to be independent of usize representation.

Prefer shuffle if this isn't important.

See intRangeLessThan, which this function uses, for commentary on the runtime of this function.

Random.shuffleWithIndex
pub fn shuffleWithIndex(r: Random, comptime T: type, buf: []T, comptime Index: type) void

File

lib/std/Random.zig:385

Code

pub fn shuffleWithIndex(r: Random, comptime T: type, buf: []T, comptime Index: type) void {
    const MinInt = MinArrayIndex(Index);
    if (buf.len < 2) {
        return;
    }

    // `i <= j < max <= maxInt(MinInt)`
    const max: MinInt = @intCast(buf.len);
    var i: MinInt = 0;
    while (i < max - 1) : (i += 1) {
        const j: MinInt = @intCast(r.intRangeLessThan(Index, i, max));
        mem.swap(T, &buf[i], &buf[j]);
    }
}