zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit d0c8fd2ce90805a6097e7b9d7a563b27e23e824c (tree)
parent ad3828db45b7830d5953e7c728c227e78f574cf9
Author: GasInfinity <me@gasinfinity.dev>
Date:   Tue, 13 Jan 2026 22:16:51 +0100

feat(std.Random): add a linear congruent generator

Diffstat:
Mlib/std/Random.zig | 1+
Alib/std/Random/lcg.zig | 28++++++++++++++++++++++++++++
2 files changed, 29 insertions(+), 0 deletions(-)

diff --git a/lib/std/Random.zig b/lib/std/Random.zig @@ -26,6 +26,7 @@ pub const Sfc64 = @import("Random/Sfc64.zig"); pub const RomuTrio = @import("Random/RomuTrio.zig"); pub const SplitMix64 = @import("Random/SplitMix64.zig"); pub const ziggurat = @import("Random/ziggurat.zig"); +pub const lcg = @import("Random/lcg.zig"); /// Any comparison of this field may result in illegal behavior, since it may be set to /// `undefined` in cases where the random implementation does not have any associated diff --git a/lib/std/Random/lcg.zig b/lib/std/Random/lcg.zig @@ -0,0 +1,28 @@ +//! Linear congruential generator +//! +//! X(n+1) = (a * Xn + c) mod m +//! +//! PRNG + +const std = @import("std"); + +/// Linear congruent generator where the modulo is `std.math.maxInt(T)`, +/// wrapping over the integer. +pub fn Wrapping(comptime T: type) type { + return struct { + xi: T, + a: T, + c: T, + + pub fn init(xi: T, a: T, c: T) LcgSelf { + return .{ .xi = xi, .a = a, .c = c }; + } + + pub fn next(lcg: *LcgSelf) T { + lcg.xi = (lcg.a *% lcg.xi) +% lcg.c; + return lcg.xi; + } + + const LcgSelf = @This(); + }; +}