Improved shuffle
All checks were successful
Java CI / Build (push) Successful in 1m33s

This commit is contained in:
Stijn Bannink 2025-04-03 22:41:21 +02:00
parent 4d6526b3a4
commit f474ff3ed6
Signed by: SBDeveloper
GPG key ID: B730712F2C3A9D7A

View file

@ -1,7 +1,7 @@
package tech.sbdevelopment.themeparkaudio.api.maps;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
/**
* An {@link ArrayList} with shuffle support.
@ -9,15 +9,14 @@ import java.util.Random;
* @param <E> The type you want to store
*/
public class SongList<E> extends ArrayList<E> {
private final Random r = new Random();
/**
* Shuffle this List
* Shuffle this List using the Fisher-Yates algorithm
*/
public void shuffle() {
for (int index = 0; index < size(); index++) {
int secondIndex = r.nextInt(size());
swap(index, secondIndex);
ThreadLocalRandom rnd = ThreadLocalRandom.current();
for (int i = size() - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
swap(index, i);
}
}
@ -29,7 +28,7 @@ public class SongList<E> extends ArrayList<E> {
public E getRandom() {
int size = size();
if (size == 0) return null;
return get(r.nextInt(size()));
return get(ThreadLocalRandom.current().nextInt(size));
}
/**
@ -39,10 +38,8 @@ public class SongList<E> extends ArrayList<E> {
* @param secondIndex The second index
*/
private void swap(int firstIndex, int secondIndex) {
E first = get(firstIndex);
E second = get(secondIndex);
set(secondIndex, first);
set(firstIndex, second);
E temp = get(firstIndex);
set(firstIndex, get(secondIndex));
set(secondIndex, temp);
}
}