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 <chrono>
5#include <random>
6"""
8c"""
9static std::default_random_engine generator(
10 std::chrono::system_clock::now().time_since_epoch().count());
11"""
13func random() -> f64:
14 """Returns a pseudo random floating point number in the range [0.0,
15 1.0] (inclusive).
17 """
19 value: f64 = 0.0
21 c"""
22 std::uniform_real_distribution<f64> distribution(0.0, 1.0);
24 value = distribution(generator)
25 """
27 return value
29func randint(minimum: i64, maximum: i64) -> i64:
30 """Returns a pseudo random integer number in the range [minimum,
31 maximum] (inclusive).
33 """
35 value: i64 = 0
37 c"""
38 std::uniform_int_distribution<i64> distribution(minimum, maximum);
40 value = distribution(generator)
41 """
43 return value
45func randfloat(minimum: f64, maximum: f64) -> f64:
46 """Returns a pseudo random floating point number in the range
47 [minimum, maximum] (inclusive).
49 """
51 value: f64 = 0.0
53 c"""
54 std::uniform_real_distribution<f64> distribution(minimum, maximum);
56 value = distribution(generator)
57 """
59 return value
61func randbytes(length: i64) -> bytes:
62 """Returns given number of pseudo random bytes.
64 """
66 value = b""
68 for i in range(length):
69 value += u8(randint(0, 255))
71 return value
73@generic(T)
74func shuffle(values: [T]):
75 """Shuffle the values in place.
77 """
79 length = values.length()
81 for current in range(length):
82 other = randint(0, length - 1)
83 value = values[current]
84 values[current] = values[other]
85 values[other] = value
87test random():
88 value = random()
89 assert value >= 0.0
90 assert value <= 1.0
92test randint():
93 value = randint(-1, 2)
94 assert value >= -1
95 assert value <= 2
96 values: [i64] = [-1, 0, 1, 2]
97 assert value in values
99test randfloat():
100 value = randfloat(-2.5, 2.0)
101 assert value >= -2.51
102 assert value <= 2.01
104test randbytes():
105 assert randbytes(0).length() == 0
106 assert randbytes(5).length() == 5
108test shuffle():
109 values = [1, 2, 3]
111 while True:
112 shuffle[i64](values)
114 if values != [1, 2, 3]:
115 break