1 /**
2  * Description: For generating random numbers.
3  *
4  * Author          Create/Modi     Note
5  * Xiaofeng Xie    Feb 22, 2001
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * Please acknowledge the author(s) if you use this code in any way.
18  *
19  * @version 1.0
20  * @Since MAOS1.0
21  */
22 
23 package net.adaptivebox.global;
24 
25 import java.util.Random;
26 
27 public class RandomGenerator {
28   /**
29    * Pseudo-random number generator instance.
30    */
31   private static Random PRNG = new Random();
32 
33   /**
34    * This function returns a random integer number between the lowLimit and
35    * upLimit.
36    *
37    * @param lowLimit lower limits upLimit The upper limits (between which the
38    *                 random number is to be generated)
39    * @return int return value Example: for find [0,1,2]
40    */
intRangeRandom(int lowLimit, int upLimit)41   public static int intRangeRandom(int lowLimit, int upLimit) {
42     int num = lowLimit + PRNG.nextInt(upLimit - lowLimit + 1);
43     return num;
44   }
45 
46   /**
47    * This function returns a random float number between the lowLimit and upLimit.
48    *
49    * @param lowLimit lower limits upLimit The upper limits (between which the
50    *                 random number is to be generated)
51    * @return double return value
52    */
doubleRangeRandom(double lowLimit, double upLimit)53   public static double doubleRangeRandom(double lowLimit, double upLimit) {
54     double num = lowLimit + PRNG.nextDouble() * (upLimit - lowLimit);
55     return num;
56   }
57 
randomSelection(int maxNum, int times)58   public static int[] randomSelection(int maxNum, int times) {
59     if (maxNum < 0) {
60       maxNum = 0;
61     }
62 
63     if (times < 0) {
64       times = 0;
65     }
66 
67     int[] all = new int[maxNum];
68     for (int i = 0; i < all.length; i++) {
69       all[i] = i;
70     }
71 
72     /* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle */
73     int[] indices = new int[Math.min(maxNum, times)];
74     for (int i = 0, j, value; i < indices.length; i++) {
75       j = intRangeRandom(i, all.length - 1);
76 
77       value = all[j];
78       all[j] = all[i];
79       indices[i] = all[i] = value;
80     }
81 
82     return indices;
83   }
84 }
85