PandaLib/src/main/java/fr/pandacube/util/RandomUtil.java

47 lines
1.0 KiB
Java
Raw Normal View History

2019-10-26 23:15:49 +02:00
package fr.pandacube.util;
2018-07-21 17:57:44 +02:00
import java.util.List;
import java.util.Random;
2019-03-15 19:01:34 +01:00
import java.util.Set;
public class RandomUtil {
public static Random rand = new Random();
public static int nextIntBetween(int minInclu, int maxExclu) {
return rand.nextInt(maxExclu - minInclu) + minInclu;
}
public static double nextDoubleBetween(double minInclu, double maxExclu) {
return rand.nextDouble() * (maxExclu - minInclu) + minInclu;
}
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");
}
}