2019-10-26 23:15:49 +02:00
|
|
|
package fr.pandacube.util;
|
2016-02-16 20:07:51 +01:00
|
|
|
|
2018-07-21 17:57:44 +02:00
|
|
|
import java.util.List;
|
2016-02-16 20:07:51 +01:00
|
|
|
import java.util.Random;
|
2019-03-15 19:01:34 +01:00
|
|
|
import java.util.Set;
|
2016-02-16 20:07:51 +01:00
|
|
|
|
|
|
|
public class RandomUtil {
|
2016-07-14 14:22:23 +02:00
|
|
|
|
2016-02-16 20:07:51 +01:00
|
|
|
public static Random rand = new Random();
|
2016-07-14 14:22:23 +02:00
|
|
|
|
2016-02-16 20:07:51 +01:00
|
|
|
public static int nextIntBetween(int minInclu, int maxExclu) {
|
2016-07-14 14:22:23 +02:00
|
|
|
return rand.nextInt(maxExclu - minInclu) + minInclu;
|
2016-02-16 20:07:51 +01:00
|
|
|
}
|
2016-07-14 14:22:23 +02:00
|
|
|
|
2016-02-16 20:07:51 +01:00
|
|
|
public static double nextDoubleBetween(double minInclu, double maxExclu) {
|
2016-07-14 14:22:23 +02:00
|
|
|
return rand.nextDouble() * (maxExclu - minInclu) + minInclu;
|
2016-02-16 20:07:51 +01:00
|
|
|
}
|
2018-07-21 17:57:44 +02:00
|
|
|
|
|
|
|
public static <T> T arrayElement(T[] arr) {
|
|
|
|
return arr[rand.nextInt(arr.length)];
|
|
|
|
}
|
|
|
|
|
|
|
|
public static <T> T listElement(List<T> arr) {
|
|
|
|
return arr.get(rand.nextInt(arr.size()));
|
|
|
|
}
|
2019-03-15 19:01:34 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns a random value from a set.
|
|
|
|
*
|
|
|
|
* May not be optimized (Actually O(n) )
|
|
|
|
* @param arr
|
|
|
|
* @return
|
|
|
|
*/
|
|
|
|
public static <T> T setElement(Set<T> set) {
|
|
|
|
if (set.isEmpty())
|
|
|
|
throw new IllegalArgumentException("set is empty");
|
|
|
|
int retI = rand.nextInt(set.size()), i = 0;
|
|
|
|
for (T e : set) {
|
|
|
|
if (retI == i)
|
|
|
|
return e;
|
|
|
|
i++;
|
|
|
|
}
|
|
|
|
throw new RuntimeException("Should never go to this line of code");
|
|
|
|
}
|
2016-02-16 20:07:51 +01:00
|
|
|
|
|
|
|
}
|