Add WorldRandom.pick and shuffle so stages need no JDK random APIs

pick(items) is items.get(nextInt(items.size())) and throws on an empty
list. shuffle(items) is Fisher-Yates from the last index down, swapping
i with nextInt(i + 1). RandomAccess lists swap through List.set; other
lists are shuffled in an array copy and written back through their
ListIterator, with the same result. Both are pinned to the Python
reference, including draw counts.
This commit is contained in:
piexel committed 2026-10-06 11:48:44 +02:00
1 parent 525c372fc5
commit 8b7accd19d
5 files changed
+193 -7

No files matched your search

@@ -1,5 +1,10 @@
package com.volmit.random;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.RandomAccess;
/** A random stream whose every value is defined here, so the same seed gives the same draws on
* every machine and every JDK. World generation draws from it: stages through
* {@link com.volmit.stage.StageContext#random()}, object generators through
@@ -29,7 +34,10 @@ package com.volmit.random;
* for ranges wider than the largest double);</li>
* <li>{@code nextGaussian()}: Marsaglia's polar method on pairs of {@code nextDouble()} values,
* using {@link StrictMath}, whose results are fixed;</li>
* <li>{@code chance(p)}: {@code nextDouble() < p}.</li>
* <li>{@code chance(p)}: {@code nextDouble() < p};</li>
* <li>{@code pick(items)}: {@code items.get(nextInt(items.size()))};</li>
* <li>{@code shuffle(items)}: Fisher-Yates, for {@code i} from {@code size - 1} down to {@code 1}
* swapping index {@code i} with {@code nextInt(i + 1)}.</li>
* </ul>
* Methods without rejection draw exactly one value. {@code nextInt(0, n)} equals {@code nextInt(n)}
* and {@code nextLong(0, n)} equals {@code nextLong(n)}.
@@ -158,6 +166,53 @@ public final class WorldRandom {
return nextDouble() < probability;
}
/** One element chosen uniformly: {@code items.get(nextInt(items.size()))}, so it draws exactly what
* {@link #nextInt(int)} draws. Throws if {@code items} is empty.
*/
public <T> T pick(List<T> items) {
if (items.isEmpty()) throw new IllegalArgumentException("cannot pick from an empty list");
return items.get(nextInt(items.size()));
}
/** Shuffles {@code items} in place by Fisher-Yates: for {@code i} from {@code size - 1} down to
* {@code 1}, swap the elements at {@code i} and {@code nextInt(i + 1)}. A list of {@code n >= 2}
* elements takes {@code n - 1} {@code nextInt} calls; a shorter list draws nothing and is not touched.
*
* <p>{@link RandomAccess} lists are swapped through {@link List#set}. Other lists, such as
* {@link java.util.LinkedList}, are copied to an array, shuffled there and written back through
* their {@link ListIterator}, like {@link Collections#shuffle}; the result is the same. A list that
* does not support {@code set} throws its {@link UnsupportedOperationException} before any element
* changes.
*/
public void shuffle(List<?> items) {
if (items.size() < 2) return;
if (items instanceof RandomAccess) {
fisherYates(items.size(), (i, j) -> Collections.swap(items, i, j));
return;
}
shuffleThroughArray(items);
}
private void shuffleThroughArray(List<?> items) {
Object[] copy = items.toArray();
fisherYates(copy.length, (i, j) -> {
Object swapped = copy[i];
copy[i] = copy[j];
copy[j] = swapped;
});
@SuppressWarnings("unchecked")
ListIterator<Object> writer = (ListIterator<Object>) items.listIterator();
for (Object item : copy) {
writer.next();
writer.set(item);
}
}
/** The one place the shuffle order is defined, so both list kinds give the same result. */
private void fisherYates(int size, IndexSwap swap) {
for (int i = size - 1; i > 0; i--) swap.swap(i, nextInt(i + 1));
}
/** Lemire's method for {@code range} in {@code [1, 2^32]}: high half of a 32-by-32-bit product. */
private long boundedInt(long range) {
long product = (nextLong() >>> INT_BITS) * range;
@@ -196,6 +251,11 @@ public final class WorldRandom {
return new IllegalArgumentException("origin must be below bound: [" + origin + ", " + bound + ")");
}
@FunctionalInterface
private interface IndexSwap {
void swap(int i, int j);
}
private static long mix(long value) {
value = (value ^ (value >>> 30)) * 0xbf58476d1ce4e5b9L;
value = (value ^ (value >>> 27)) * 0x94d049bb133111ebL;
@@ -3,7 +3,10 @@ package com.volmit.random;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
@@ -123,6 +126,78 @@ class WorldRandomTest {
assertEquals(List.of(true), draws(REPEATS, random -> random.chance(1)).stream().distinct().toList());
}
@Test
void pickTakesTheElementAtNextInt() {
assertEquals(List.of("h", "b", "c", "d", "a", "i"),
draws(6, random -> random.pick(List.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"))));
}
@Test
void shuffleIsFisherYatesFromTheLastIndexDown() {
assertEquals(List.of(), shuffled(0));
assertEquals(List.of(0), shuffled(1));
assertEquals(List.of(0, 1), shuffled(2));
assertEquals(List.of(8, 3, 6, 5, 4, 0, 9, 2, 1, 7), shuffled(10));
}
/** The first {@code nextInt(2)} is 1, which keeps the pair; the second is 0, which swaps it. */
@Test
void shuffleSwapsAPairWhenNextIntIsZero() {
var random = new WorldRandom(SEED);
var pair = new ArrayList<>(List.of(0, 1));
random.shuffle(pair);
assertEquals(List.of(0, 1), pair);
random.shuffle(pair);
assertEquals(List.of(1, 0), pair);
}
@Test
void shuffleGivesTheSameResultForListsWithoutRandomAccess() {
var linked = new LinkedList<>(range(10));
new WorldRandom(SEED).shuffle(linked);
assertEquals(shuffled(10), linked);
}
@Test
void shuffleOfAListWithoutSetThrowsAndLeavesItUnchanged() {
var fixed = List.of(0, 1, 2);
var unmodifiableLinked = Collections.unmodifiableList(new LinkedList<>(fixed));
assertThrows(UnsupportedOperationException.class, () -> new WorldRandom(SEED).shuffle(fixed));
assertThrows(UnsupportedOperationException.class, () -> new WorldRandom(SEED).shuffle(unmodifiableLinked));
assertEquals(fixed, unmodifiableLinked);
}
@Test
void shuffleOfFewerThanTwoElementsTouchesNothing() {
assertDoesNotThrow(() -> new WorldRandom(SEED).shuffle(List.of(0)));
assertDoesNotThrow(() -> new WorldRandom(SEED).shuffle(Collections.unmodifiableList(new LinkedList<>(List.of(0)))));
}
@Test
void pickFromAnEmptyListThrows() {
assertThrows(IllegalArgumentException.class, () -> new WorldRandom(SEED).pick(List.of()));
}
/** {@code pick} draws what {@code nextInt(size)} draws; a shuffle of {@code n >= 2} elements draws
* {@code n - 1} values (no rejection at these bounds and seed), a shorter one nothing.
*/
@Test
void listHelpersDrawAFixedNumberOfValues() {
var longs = draws(10, WorldRandom::nextLong);
var picked = new WorldRandom(SEED);
picked.pick(List.of("a", "b", "c"));
assertEquals(longs.get(1), picked.nextLong());
for (int size : new int[] {0, 1, 2, 10}) {
var random = new WorldRandom(SEED);
random.shuffle(new ArrayList<>(range(size)));
assertEquals(longs.get(Math.max(size - 1, 0)), random.nextLong(), "shuffle of " + size);
}
}
@Test
void zeroOriginRangesEqualTheSingleBoundMethods() {
assertEquals(draws(REPEATS, random -> random.nextInt(37)), draws(REPEATS, random -> random.nextInt(0, 37)));
@@ -175,7 +250,18 @@ class WorldRandomTest {
assertEquals(Set.of("nextLong()", "nextLong(long)", "nextLong(long,long)", "nextInt()", "nextInt(int)",
"nextInt(int,int)", "nextBoolean()", "nextFloat()", "nextDouble()", "nextDouble(double)",
"nextDouble(double,double)", "nextGaussian()", "chance(double)"), methods);
"nextDouble(double,double)", "nextGaussian()", "chance(double)", "pick(java.util.List)",
"shuffle(java.util.List)"), methods);
}
private static List<Integer> shuffled(int size) {
var items = new ArrayList<>(range(size));
new WorldRandom(SEED).shuffle(items);
return items;
}
private static List<Integer> range(int size) {
return Stream.iterate(0, i -> i + 1).limit(size).toList();
}
private static String signature(Method method) {
+32
View File
@@ -177,6 +177,25 @@ class WorldRandom:
def chance(self, probability):
return self.next_double() < probability
def pick(self, items):
return items[self.next_int_bound(len(items))]
def shuffle(self, items):
"""Fisher-Yates from the last index down to 1, swapping each with a nextInt(i + 1) index."""
for i in range(len(items) - 1, 0, -1):
j = self.next_int_bound(i + 1)
items[i], items[j] = items[j], items[i]
class CountingRandom(WorldRandom):
def __init__(self, seed):
super().__init__(seed)
self.draws = 0
def raw(self):
self.draws += 1
return super().raw()
def below(value):
bits = struct.unpack("<q", struct.pack("<d", value))[0]
@@ -216,3 +235,16 @@ if __name__ == "__main__":
draws("nextDouble(-MAX, MAX)", lambda r: r.next_double_range(-max_double, max_double))
draws("nextGaussian()", WorldRandom.next_gaussian)
draws("chance(0.25)", lambda r: r.chance(0.25), count=12)
draws("pick(a..j)", lambda r: r.pick("abcdefghij"))
for size in (0, 1, 2, 10):
random = CountingRandom(42)
items = list(range(size))
random.shuffle(items)
print(f"shuffle(0..{size - 1}): {items}, {random.draws} draws")
# The first nextInt(2) is 1, which keeps [0, 1]; the second is 0, which swaps.
random = WorldRandom(42)
pair = [0, 1]
random.shuffle(pair)
first = list(pair)
random.shuffle(pair)
print(f"shuffle([0, 1]) twice on one stream: {first}, {pair}")