add shuffle method

This commit is contained in:
2017-12-08 18:27:55 +01:00
parent c41e52f8b3
commit 29d4e49298
2 changed files with 63 additions and 2 deletions

View File

@@ -3,7 +3,9 @@ package org.lucares.collections;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Spliterator.OfInt;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;
@@ -483,6 +485,35 @@ public final class IntList implements Serializable, Cloneable {
sorted = true;
}
/**
* Shuffles the list. The permutation is uniformly distributed.
*/
public void shuffle() {
shuffle(ThreadLocalRandom.current());
}
/**
* Shuffles the list. The permutation is uniformly distributed.
*
* @param random
* the random number generator used
*/
public void shuffle(final Random random) {
/*
* See Knuth, Donald E. Seminumerical algorithms. (1998). The Art of Computer
* Programming. 2. AddisonWesley pp. 145146. Algorithm P and exercise 18.
*/
for (int i = size() - 1; i > 0; i--) {
final int other = random.nextInt(i);
final int tmp = data[other];
data[other] = data[i];
data[i] = tmp;
}
sorted = false;
}
private void ensureCapacity(final int newElements) {
final int requiredCapacity = size + newElements;