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