Generare numeri random in Zig

Mattepuffo's logo
Generare numeri random in Zig

Generare numeri random in Zig

In Zig abbiamo diversi modi per generare numeri random.

Qui sotto vi metto due esempi; nel secondo usiamo il crypto.

const std = @import("std");

pub fn main() !void {
    std.debug.print("Uso Random\n", .{});

    var prng: std.Random.DefaultPrng = .init(blk: {
        var seed: u64 = undefined;
        try std.posix.getrandom(std.mem.asBytes(&seed));
        break :blk seed;
    });
    const rand_prng = prng.random();

    const a_prng = rand_prng.float(f32);
    const b_prng = rand_prng.boolean();
    const c_prng = rand_prng.int(u8);
    const d_prng = rand_prng.intRangeAtMost(u8, 0, 255);

    std.debug.print("{}, {}, {}, {}\n", .{a_prng, b_prng, c_prng, d_prng});

    std.debug.print("Uso Crypto\n", .{});

    const rand = std.crypto.random;

    const a = rand.float(f32);
    const b = rand.boolean();
    const c = rand.int(u8);
    const d = rand.intRangeAtMost(u8, 0, 255);

    std.debug.print("{}, {}, {}, {}\n", .{a, b, c, d});
}

Enjoy!


Condividi

Commentami!