Add random item selection from Set

This commit is contained in:
Marc Baloup 2019-03-15 19:01:34 +01:00
parent 94138ad79a
commit e60fe99410

View File

@ -2,6 +2,7 @@ package fr.pandacube.java.util;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
import java.util.Set;
public class RandomUtil { public class RandomUtil {
@ -22,5 +23,24 @@ public class RandomUtil {
public static <T> T listElement(List<T> arr) { public static <T> T listElement(List<T> arr) {
return arr.get(rand.nextInt(arr.size())); return arr.get(rand.nextInt(arr.size()));
} }
/**
* 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");
}
} }