Skip to content

Instantly share code, notes, and snippets.

@mageddo
Created July 8, 2018 13:24
Show Gist options
  • Select an option

  • Save mageddo/a1b04d111a63f4e2cd382d7d6dc54572 to your computer and use it in GitHub Desktop.

Select an option

Save mageddo/a1b04d111a63f4e2cd382d7d6dc54572 to your computer and use it in GitHub Desktop.
Reproducible Random Generation
import org.apache.commons.lang3.reflect.FieldUtils;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
public class InvRand {
static final String SEED_FIELD = "seed";
public static void main(String[] args) throws IllegalAccessException {
final Random r = new Random(122);
final AtomicLong seed = getSeed(r);
final int size = 10;
final long[][] buffer = new long[size][2];
// generating random numbers based on seed
for (int i = 0; i < size; i++) {
final long currSeed = seed.get();
buffer[i][0] = nextInt(r, 0, 5);
buffer[i][1] = currSeed;
System.out.printf("n=%s, seed=%s%n", buffer[i][0], currSeed);
}
System.out.println("\n//======================================//\n");
// replay generated numbers from seed
for (int i = buffer.length - 1; i >= 0; i--) {
final Random r2 = new Random();
plainSetSeed(buffer[i], r2);
for (int j = 0; j < size - i; j++) {
final long currSeed = getSeed(r2).get();
System.out.printf("index=%s, original{n=%s, seed=%s}, current{n=%s, seed=%s}%n", i + j, buffer[i + j][0], buffer[i + j][1], nextInt(r2, 0, 5), currSeed);
}
System.out.println();
}
}
/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param min Minimum value
* @param max Maximum value. Must be greater than min.
* @return Integer between min and max, inclusive.
* @see java.util.Random#nextInt(int)
*/
public static int nextInt(Random r, int min, int max) {
return r.nextInt((max - min) + 1) + min;
}
private static void plainSetSeed(long[] longs, Random r2) throws IllegalAccessException {
FieldUtils.writeDeclaredField(r2, SEED_FIELD, new AtomicLong(longs[1]), true);
}
private static AtomicLong getSeed(Random r) throws IllegalAccessException {
return (AtomicLong) FieldUtils.readField(r, SEED_FIELD, true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment