Sometimes, we need to shuffle an array or list in Java – but we want to get the same “random” output for the same input. The following is a Pseudo Random Generator that is implemented in Java that shuffles an array or list using a seed.
The RANDOM_GENERATOR_NUMBER is a prime number (e.g. 999_999_000_001) and we use it to do some bit shifting and XOR. Then, we generate a random index to swap.
Prime numbers when factorization are using integers only 1 and itself. For example, prime number 999999000001 can only be represented as the product of 1 and 999999000001.
package helloacm.com;
import java.util.Arrays;
import java.util.List;
public class RandomGenerator<T> {
private static long RANDOM_GENERATOR_NUMBER = 999_999_000_001L;
public List<T> shuffle(List<T> list, long seed) {
seed = seed << 32;
final var sz = list.size();
for (int i = 0; i < sz; i++) {
long v = seed + i * RANDOM_GENERATOR_NUMBER;
v = v ^ (v >> 12);
v = v ^ (v << 25);
v = v ^ (v >> 27);
v = v * RANDOM_GENERATOR_NUMBER;
int index = (int) (i + v % (sz - i));
if (index >= 0 && index < sz) {
T tmp = list.get(index);
list.set(index, list.get(i));
list.set(i, tmp);
}
}
return list;
}
}
For example, if you run the following program to shuffle an array of 7 numbers (1 to 7):
package helloacm.com
public class Main {
public static void main(String[] args) {
List<Integer> data = Arrays.asList(new Integer[] {1, 2, 3, 4, 5, 6, 7});
RandomGenerator<Integer> rand = new RandomGenerator<>();
rand.shuffle(data, 1234);
System.out.println(data);;
}
}
It will always print:
[7, 5, 3, 4, 2, 6, 1]
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Java Program to Print All Local IP Addresses
Next Post: Teaching Kids Programming - First Unique Character in a String