-
Notifications
You must be signed in to change notification settings - Fork 1
/
rand.janet
82 lines (73 loc) · 1.74 KB
/
rand.janet
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
# rand.janet
#
# A library of various functions for getting random things.
#
# Copyright 2021 John Gabriele
(defn rand-int
``Generate a random integer i, either in 0 <= i < n,
or --- if `m` is given --- in n <= i < m.``
[n &opt m]
(when m (assert (> m n)))
(var start 0)
(var end 0)
(if m
(do
(set start n)
(set end m))
(do
(set start 0)
(set end n)))
(+ start
(math/trunc (* (math/random)
(- end start)))))
(defn rand-elem
``Choose a random element from array `arr`.``
[arr]
(get arr
(rand-int (length arr))))
(defn rand-elems
``Randomly choose `n` elements from array `arr`. Any
given element of `arr` may only be chosen once.``
[n arr]
(assert (<= n (length arr)))
(def res @[])
(def ar2 (array ;arr))
(for _ 0 n
(let [i (rand-int (length ar2))]
(array/push res (ar2 i))
(array/remove ar2 i)))
res)
(defn rand-rolls
``Like the rolls of a die, choose `n` values randomly
from the elements in the array `arr`. A given value may
be selected more than once.``
[n arr]
(var res @[])
(for _ 0 n
(array/push res
(rand-elem arr)))
res)
(defn shuffle
``Return a shuffled copy of `arr`.``
[arr]
(rand-elems (length arr) arr))
(defn rand-key
``Get a random key from table `t`.``
[t]
(rand-elem (keys t)))
(defn rand-val
``Get a random value from table `t`.``
[t]
(rand-elem (values t)))
(defn rand-kv
``Get a random key/value pair (as a tuple) from
table `t`.``
[t]
(rand-elem (pairs t)))
(defn rand-str
``Generate a random lowercase ascii string,
`n` characters long.``
[n]
(def ltrs (map string/from-bytes
"abcdefghijklmnopqrstuvwxyz"))
(string/join (rand-rolls n ltrs)))