Randomization makes quiz-style games more effective by presenting questions in an unpredictable order. If you have a java.util.List of questions, then this will randomize the list.
Collections.shuffle(listOfQuestions);
However, you may not want to transform the original list. Or, you want to provide additional filtering in the construction of the randomized list. You might write a procedure like this.
public List<Integer> randomPermutation(Integer numItems) {
List<Integer> perm = new ArrayList<>();
Integer selectedItems = 0;
Random random = new Random();
while( selectedItems < numItems ) {
Integer i = random.nextInt(numItems);
if( !perm.contains(i) ) {
perm.add( i );
selectedItems++;
}
}
return perm;
}
The function gathers a list of unique integers within the range 0 to numItems. The while loop may run more than numItems times, depending on whether or not there are collisions.
Java 8 Streams
Using the Random.ints() method instead of the Random.nextInt() method, we can skip the iteration in favor of a function. The following function re-implements randomPermutation().
public List<Integer> randomPermutation2(Integer numItems) {
return new Random().
ints(0, numItems).
distinct().
limit(numItems).
boxed().
collect(Collectors.toList());
}
Let's break this down.
- new Random().ints(0, numItems) - Return an unlimited stream of primitive ints between 0 (inclusive) and numItems (exclusive)
- distinct() - A stateful check that only unique items are returned
- limit(numItems) - Limits the unlimited stream to the number of items we care about
- boxed() - Convert int to Integer; alternatively, call "mapToObj(i -> new Integer(i))"
- collect(Collectors.toList()) - Turn the stream into a java.utilList for returning
No comments:
Post a Comment