Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# pylint:disable=unused-argument
3c"""source-before-namespace
4#include <random>
5"""
7c"""
8static std::random_device device;
9"""
11func random() -> f64:
12 """Returns a cryptographically safe random floating point number in
13 the range [0.0, 1.0] (inclusive).
15 """
17 value: f64 = 0.0
19 c"""
20 std::uniform_real_distribution<f64> distribution(0.0, 1.0);
22 value = distribution(device)
23 """
25 return value
27func randint(minimum: i64, maximum: i64) -> i64:
28 """Returns a cryptographically safe random integer number in the range
29 [minimum, maximum] (inclusive).
31 """
33 value: i64 = 0
35 c"""
36 std::uniform_int_distribution<i64> distribution(minimum, maximum);
38 value = distribution(device)
39 """
41 return value
43func randfloat(minimum: f64, maximum: f64) -> f64:
44 """Returns a cryptographically safe random floating point number in
45 the range [minimum, maximum] (inclusive).
47 """
49 value: f64 = 0.0
51 c"""
52 std::uniform_real_distribution<f64> distribution(minimum, maximum);
54 value = distribution(device)
55 """
57 return value
59func randbytes(length: i64) -> bytes:
60 """Returns given number of cryptographically safe random bytes.
62 """
64 value = b""
66 for i in range(length):
67 value += u8(randint(0, 255))
69 return value
71@generic(T)
72func shuffle(values: [T]):
73 """Shuffle the values in place.
75 """
77 length = values.length()
79 for current in range(length):
80 other = randint(0, length - 1)
81 value = values[current]
82 values[current] = values[other]
83 values[other] = value
85test random():
86 value = random()
87 assert value >= 0.0
88 assert value <= 1.0
90test randint():
91 value = randint(-1, 2)
92 assert value >= -1
93 assert value <= 2
94 values: [i64] = [-1, 0, 1, 2]
95 assert value in values
97test randfloat():
98 value = randfloat(-2.5, 2.0)
99 assert value >= -2.51
100 assert value <= 2.01
102test randbytes():
103 assert randbytes(0).length() == 0
104 assert randbytes(5).length() == 5
106test shuffle():
107 values = [1, 2, 3]
109 while True:
110 shuffle[i64](values)
112 if values != [1, 2, 3]:
113 break