1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
use math::random;
use fmt;
use time;
use getopt;
use os;
use strconv;
use sort;
use sort::cmp;
use io;
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 number than can be generated (default: 110)"),
('S', "separator", "The separator to use when displaying the numbers (default: \\n)"),
('s', "Sort the numbers"),
('d', "Avoid duplicates"));
defer getopt::finish(&cmd);
let nb = 6z;
let max = 110u32;
let sep = "\n";
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' =>
sep = opt.1;
case 's' =>
dosort = true;
case 'd' =>
nodups = true;
case => abort();
};
};
if (nodups && max < nb) {
fmt::fatal("Can't generate the desired number of randoms without duplicates");
};
const seed = time::unix(time::now(time::clock::MONOTONIC));
const r = random::init(seed: u32);
let rngs: []u32 = [];
defer free(rngs);
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);
};
match (printrngs(rngs, sep)) {
case void =>
yield;
case let e: io::error =>
fmt::fatal(io::strerror(e));
};
};
fn printrngs(rngs: []u32, sep: str) (void | io::error) = {
let s = "";
for (const rng .. rngs) {
fmt::printf("{}{}", s, rng)?;
s = sep;
};
fmt::println()?;
};
fn contains(a: []u32, b: u32) bool = {
for (const l .. a) {
if (l == b) {
return true;
};
};
return false;
};
|