random.anubis
1.5 KB
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
87
88
89
90
91
92
93
read system/string.anubis
read tools/base64.anubis
read tools/string.anubis
read list.anubis
define String
_random_string
(
Int size,
String current
)=
if size = 0 then
current
else
_random_string( size - 1, current + random(9))
.
/** generate_random_string
* generate and return an ASCII readable random string with length of size
*
*/
public define String
generate_random_string
(
Int size
) =
to_string(extract(base64_encode(to_byte_array(_random_string(size, ""))), 0, size)).
*** (4.6) Randomly shuffling a list.
*** (4.6.1) Basic Shuffling
define List($T)
insert_at_position
(
Word32 pos,
$T h,
List($T) t
) =
if pos = 0
then [h . t]
else if t is
{
[ ] then [h],
[a . b] then
[a . insert_at_position(pos-1,h,b)]
}.
define List($T)
random_insert
(
$T h,
List($T) t
) =
with n = truncate_to_Word32(length(t)),
r = random(n+1),
insert_at_position(r,h,t).
public define List($T)
shuffle
(
List($T) l
) =
if l is
{
[ ] then [ ],
[h . t] then random_insert(h,shuffle(t))
}.
*** (4.6.2) Shuffling a non empty list.
public define NonEmptyList($T)
shuffle
(
NonEmptyList($T) l
) =
if l is [h . t] then
if shuffle((List($T))[h . t]) is
{
[ ] then l, // cannot happen
[h2 . t2] then [h2 . t2]
}.