diff --git a/lib/std/Random.zig b/lib/std/Random.zig index 218ddac1d6..ee2185d301 100644 --- 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 new file mode 100644 index 0000000000..d63ff9c829 --- /dev/null +++ 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(); + }; +}