Random
std.Random randomly generates numbers and other values:
const std = @import("std");
const print = std.debug.print;
pub fn main() void {
// Using the default random number generator:
var prng = std.Random.DefaultPrng.init(0);
const r = prng.random();
// 'int' generates a value of an integer type:
print("Integers:\n ", .{});
for (0..8) |_|
print(" {}", .{r.int(i8)});
print("\n", .{});
// Limit the range of generated integers:
print("Integers in 0..99:\n ", .{});
for (0..8) |_| {
// intRangeAtMost(i8, 0, 99) would also work
const n = r.intRangeLessThan(i8, 0, 100);
print(" {}", .{n});
}
print("\n", .{});
// Generate floats:
print("Floats:\n ", .{});
for (0..8) |_|
print(" {d:.2}", .{r.float(f64)});
print("\n", .{});
// Generate booleans:
print("Booleans:\n ", .{});
for (0..8) |_|
print(" {}", .{r.boolean()});
print("\n", .{});
// Generate values of an enum type:
print("Enum values:\n ", .{});
const Color = enum { red, green, blue };
for (0..8) |_|
print(" {}", .{r.enumValue(Color)});
print("\n", .{});
// Use 'shuffle' to shuffle a slice in place:
print("Shuffle a slice:\n ", .{});
var array = [_]u64{ 10, 20, 30, 40, 50 };
const slice: []u64 = &array;
r.shuffle(u64, slice);
for (slice) |n|
print(" {}", .{n});
print("\n", .{});
// Randomly choose an element:
print("Letters:\n ", .{});
const abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (0..8) |_|
print(" {c}", .{
abc[r.intRangeLessThan(usize, 0, abc.len)],
});
print("\n", .{});
}$ zig run random.zig
Integers:
-33 7 -4 26 -22 -102 110 89
Integers in 0..99:
99 8 40 98 75 12 97 96
Floats:
0.69 0.06 0.47 0.28 0.39 0.22 0.04 0.40
Booleans:
true true true true false false false false
Enum values:
.green .blue .blue .red .green .red .blue .red
Shuffle a slice:
30 10 40 20 50
Letters:
A E F E G L P N
Using a seed
std.Random.DefaultPrng is a pseudorandom
number generator, so the values it produces are predictable. One way
to get different values on each program run is to get a truly random
value from std.Io.random
and use that as a seed.
const std = @import("std");
const print = std.debug.print;
pub fn main(init: std.process.Init) !void {
var buf: [8]u8 = undefined;
init.io.random(&buf);
const seed = std.mem.readInt(u64, &buf, .big);
print("seed is {x}\n", .{seed});
var prng = std.Random.DefaultPrng.init(seed);
const random = prng.random();
const n = random.float(f64);
print("Random number: {d:.2}\n", .{n});
}Let’s run it a few times to check:
$ zig run random-2.zig
seed is 1cd61cdd4549ff85
Random number: 0.05
$ zig run random-2.zig
seed is 3e740ddacc19b599
Random number: 0.81
$ zig run random-2.zig
seed is b3d734d50fd25f10
Random number: 0.16
Next example: Arguments.