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

shuffleWithIndex

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

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.

Params

  • r: Random
  • T: type
  • buf: []T
  • Index: type

File

Random.zig:385
385
386
387
388
389
390
391
392
393
394
395
396
397
398
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]);
    }
}