diff --git a/DESIGN.md b/DESIGN.md index 2937574f4..e7db1a287 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -405,7 +405,7 @@ JDK defaults that a JDK update may change, and those are the ones module authors `WorldRandom` therefore does not implement `RandomGenerator`. Overriding every default would hold only until a JDK adds another one; a type of its own exposes nothing IrisApi does not define. The price is that it cannot be passed to JDK methods that take a `Random` or `RandomGenerator`, such as -`Collections.shuffle`. Its methods: +`Collections.shuffle`; `pick` and `shuffle` cover the list cases instead. Its methods: | Method | Definition | | --- | --- | @@ -418,13 +418,20 @@ price is that it cannot be passed to JDK methods that take a `Random` or `Random | `nextDouble(bound)`, `nextDouble(origin, bound)` | `origin + nextDouble() * (bound - origin)`, a result rounded up to `bound` replaced by the double below it; a width beyond `Double.MAX_VALUE` is halved first | | `nextGaussian()` | Marsaglia's polar method on `StrictMath.log` and `StrictMath.sqrt`; the pair's second value is discarded | | `chance(probability)` | `nextDouble() < probability` | +| `pick(items)` | `items.get(nextInt(items.size()))`; an empty list throws | +| `shuffle(items)` | Fisher-Yates in place: for `i` from `size - 1` down to `1`, swap `i` with `nextInt(i + 1)` | The state is one `long`, initially the seed. Methods without rejection draw exactly one value; how many values a method draws is part of the sequence. `StrictMath` is fixed bit for bit by the Java SE specification (fdlibm), so the gaussian needs no math of its own. Invalid bounds (`bound <= 0`, `origin >= bound`, NaN or infinite doubles, a probability outside `[0, 1]`) throw -`IllegalArgumentException`. The generator is not thread-safe: one stage uses its stream within one -invocation. +`IllegalArgumentException`, as does `pick` on an empty list. `pick` draws what `nextInt(size)` +draws. A shuffle of `n >= 2` elements makes `n - 1` `nextInt` calls; a shorter list draws nothing +and is not touched. `RandomAccess` lists are swapped through `List.set`; other lists are copied to +an array, shuffled there and written back through their `ListIterator`, like `Collections.shuffle`, +with the same result. A list that does not support `set` throws its `UnsupportedOperationException` +before any element changes. Weighted picking is left out until a stage needs it. The generator is +not thread-safe: one stage uses its stream within one invocation. `WorldRandomTest` pins every method to values computed by `src/test/reference/world_random.py`, an independent implementation of this table with Python integers and IEEE doubles. Python's `math.log` diff --git a/README.md b/README.md index 5172b2ffb..32849bdf1 100644 --- a/README.md +++ b/README.md @@ -57,8 +57,9 @@ module may still condition its stages on it, as moss does on `iris:snow`. Stages and object generators draw from `com.volmit.random.WorldRandom`, an IrisApi type whose every method is defined and pinned by tests, so the same seed gives the same world on every JDK. It is SplitMix64 with `nextInt`, `nextLong` and `nextDouble` in plain, bounded and `origin, bound` forms, -plus `nextBoolean`, `nextFloat`, `nextGaussian` and `chance(probability)`. It does not implement -`java.util.random.RandomGenerator`, whose default methods the JDK may change. Bounded integers are +plus `nextBoolean`, `nextFloat`, `nextGaussian`, `chance(probability)`, `pick(list)` and +`shuffle(list)`. It does not implement `java.util.random.RandomGenerator`, whose default methods the +JDK may change, so use `pick` and `shuffle` instead of `Collections.shuffle`. Bounded integers are unbiased, `nextDouble` never returns its bound, and invalid bounds throw. It is not thread-safe: a stage uses its own stream within one invocation and must not share or keep it. diff --git a/src/main/java/com/volmit/random/WorldRandom.java b/src/main/java/com/volmit/random/WorldRandom.java index 0fd1d090c..17cbbfa78 100644 --- a/src/main/java/com/volmit/random/WorldRandom.java +++ b/src/main/java/com/volmit/random/WorldRandom.java @@ -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); *
  • {@code nextGaussian()}: Marsaglia's polar method on pairs of {@code nextDouble()} values, * using {@link StrictMath}, whose results are fixed;
  • - *
  • {@code chance(p)}: {@code nextDouble() < p}.
  • + *
  • {@code chance(p)}: {@code nextDouble() < p};
  • + *
  • {@code pick(items)}: {@code items.get(nextInt(items.size()))};
  • + *
  • {@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)}.
  • * * 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 pick(List 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. + * + *

    {@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 writer = (ListIterator) 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; diff --git a/src/test/java/com/volmit/random/WorldRandomTest.java b/src/test/java/com/volmit/random/WorldRandomTest.java index d1fcf0a12..42f366919 100644 --- a/src/test/java/com/volmit/random/WorldRandomTest.java +++ b/src/test/java/com/volmit/random/WorldRandomTest.java @@ -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 shuffled(int size) { + var items = new ArrayList<>(range(size)); + new WorldRandom(SEED).shuffle(items); + return items; + } + + private static List range(int size) { + return Stream.iterate(0, i -> i + 1).limit(size).toList(); } private static String signature(Method method) { diff --git a/src/test/reference/world_random.py b/src/test/reference/world_random.py index d3784e4d6..c35edb6d2 100644 --- a/src/test/reference/world_random.py +++ b/src/test/reference/world_random.py @@ -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("