commit 8b5ae05610740739f6412b9458ac21854add6d0d parent 890133e0e125cbb13b5cda0cf36258052fde5c01 Author: Sebastian <sebastian@sebsite.pw> Date: Sun, 1 Dec 2024 19:50:38 -0500 math::random: seed from current time if seed not provided Signed-off-by: Sebastian <sebastian@sebsite.pw> Diffstat:
M | math/random/random.ha | | | 15 | +++++++++++++-- |
1 file changed, 13 insertions(+), 2 deletions(-)
diff --git a/math/random/random.ha b/math/random/random.ha @@ -1,12 +1,23 @@ // SPDX-License-Identifier: MPL-2.0 // (c) Hare authors <https://harelang.org> +use time; + // State for a pseudorandom number generator. export type random = u64; // Initializes a pseudorandom number generator with a given seed. This seed will -// yield the same sequence of psuedo-random numbers if used again. -export fn init(seed: u64) random = seed; +// yield the same sequence of psuedo-random numbers if used again. If 'seed' is +// void, the seed is instead determined by the current time (as reported by +// [[time::now]]). +export fn init(seed: (u64 | void) = void) random = { + match (seed) { + case void => + return time::now(time::clock::MONOTONIC).sec: random; + case let r: u64 => + return r; + }; +}; // Returns a psuedo-random 64-bit unsigned integer. export fn next(r: *random) u64 = {