From a09cb90dec5a8c5ba388c4189462ad334186aa46 Mon Sep 17 00:00:00 2001 From: Julian Hurst Date: Mon, 16 Sep 2024 17:05:36 +0200 Subject: Initial commit --- rng.ha | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 rng.ha diff --git a/rng.ha b/rng.ha new file mode 100644 index 0000000..522e0d4 --- /dev/null +++ b/rng.ha @@ -0,0 +1,64 @@ +use math::random; +use fmt; +use time; +use getopt; +use os; +use strconv; +use sort; +use sort::cmp; + +export fn main() void = { + const cmd = getopt::parse(os::args, + "Random Number Generator", + ('n', "number", "Number of random numbers to print (default: 6)"), + ('m', "max", "Max range to print to (default: 110)"), + ('s', "Sort the numbers"), + ('d', "Avoid duplicates")); + defer getopt::finish(&cmd); + + let nb = 6z; + let max = 110u32; + let dosort = false; + let nodups = false; + for (let opt .. cmd.opts) { + switch (opt.0) { + case 'n' => + nb = strconv::stoz(opt.1)!; + case 'm' => + max = strconv::stou32(opt.1)!; + case 's' => + dosort = true; + case 'd' => + nodups = true; + case => abort(); + }; + }; + + let seed = time::unix(time::now(time::clock::MONOTONIC)); + let r = random::init(seed: u32); + let rngs: []u32 = []; + for (let i = 0z; i < nb; i+= 1) { + let a = random::u32n(&r, max) + 1; + for (nodups && contains(rngs, a)) { + a = random::u32n(&r, max) + 1; + }; + append(rngs, a); + }; + + if (dosort) { + sort::sort(rngs: []opaque, size(u32), &cmp::u32s); + }; + + for (let rng .. rngs) { + fmt::printfln("{}", rng)!; + }; +}; + +fn contains(a: []u32, b: u32) bool = { + for (const l .. a) { + if (l == b) { + return true; + }; + }; + return false; +}; -- cgit v1.2.3