Use of Random

I am afraid the std.Random.zig is unreadable for me. No useful comments provided. Strange anytype pointers..
How can I generate some random numbers 0 <= r <= 9?

const std = @import("std");

pub fn main() !void {
    // userland rng implementation
    var prng = std.Random.DefaultPrng.init(seed: {
        var seed: u64 = undefined;
        // get random seed from OS
        try std.posix.getrandom(std.mem.asBytes(&seed));
        break :seed seed;
    });
    // get interface
    const rand = prng.random();
    const n = rand.intRangeAtMost(u8, 0, 9);
    std.debug.print("{}", .{n});
}
3 Likes

Some Alternatives

  • Use crypto to generate the seed:
const seed = std.crypto.random.int(u64);
var prng = std.Random.DefaultPrng.init(seed);
const rand = prng.random();
_ = rand.uintAtMost(u4, 9);
  • When testing there is std.testing.seed:
var prng = std.Random.DefaultPrng.init(std.testing.seed);
const rand = prng.random();
_ = rand.uintAtMost(u4, 9);

Note that prng must be var to hold the random generator state.

9 Likes

Thanks!
Writing Zig is easier then reading.

We also have PRNG module in TigerBeetle:

This is mostly to avoid stdlib churn, but I also cleaned up the API to my taste somewhat (e.g.), and we have a second fun implementation of the same API here (and a third one, finite rng, is on my todo list…)

2 Likes