Add random item selection from Set
This commit is contained in:
parent
94138ad79a
commit
e60fe99410
@ -2,6 +2,7 @@ package fr.pandacube.java.util;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
|
||||
public class RandomUtil {
|
||||
|
||||
@ -23,4 +24,23 @@ public class RandomUtil {
|
||||
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");
|
||||
}
|
||||
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user