1 module lib.random.random;  //FIXME the module name is too nested
2 
3 import std.random : uniform;
4 import lib.exception : ValueError;
5 
6 /**
7 Returns random numbers from [low, high$(RPAREN).
8 The random numbers are uniformly distributed.
9 
10 Parameters:
11     low = The beginning of the range of the distribution.
12     high = The end of the range of the distribution.
13     size = The size of the array.
14  */
15 T[] randomArray(T) (T low, T high, ulong size) {
16     if(low >= high) {
17         throw new ValueError("low >= high");
18     }
19 
20     T[] array = new T[size];
21     foreach(ref e; array) {
22         e = uniform(low, high);
23     }
24     return array;
25 }
26 
27 
28 ///
29 unittest {
30     double low = -100.0;
31     double high = 100.0;
32     ulong size = 20;
33 
34     auto array = randomArray(low, high, size);
35     assert(array.length == size);
36     foreach(double e; array) {
37         assert(low <= e && e < high);
38     }
39 }
40 
41 
42 //Ensure it also works if the types of the arguments are long.
43 unittest {
44     long low = -100;
45     long high = 100;
46     ulong size = 20;
47 
48     auto array = randomArray(low, high, size);
49     assert(array.length == size);
50     foreach(long e; array) {
51         assert(low <= e && e < high);
52     }
53 }
54 
55 
56 //An exception must be thrown if low == high
57 unittest {
58     bool failed = false;
59     try {
60         auto array = randomArray(10, 10, 10);
61     } catch(Error e) {
62         failed = true;
63     }
64     //must fail
65     assert(failed);
66 }
67 
68 
69 //An empty array must be returned when 0 specified to the size.
70 unittest {
71     assert(randomArray(0, 10, 0) == []);
72 }