Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.j256;
- /**
- * Minimal Standard Pseudo-Random Number Generator
- *
- * Author: Fuat C. Baran, Columbia University, 1988
- *
- * Based on code in "Random Number Generators: Good Ones are Hard to Find", by Stephen K. Park and Keith W. Miller in
- * Communications of the ACM, 31, 10 (Oct. 1988) pp. 1192-1201.
- *
- * Requirements: MAXINT must be 2 ^ 31 - 1 or larger.
- *
- * This is needed so we can duplicate a random number algorithm in perl so external entities can run
- */
- public class SimpleRandom {
- /* random number generator doesn't handle 0 */
- private static final int ZERO_SEED_REPLACEMENT = 0x7EADBEEF;
- /* magic number */
- private static final int MAGIC_A = 16807;
- /* mersenne prime 2^31 -1 */
- private static final int MERSENNE_PRIME = 2147483647;
- /* M div A (M / A) */
- private static final int MAGIC_QUOTIENT = 127773;
- /* M mod A (M % A) */
- private static final int MAGIC_REMAINDER = 2836;
- private int value = 0;
- /**
- * Creates our generator with an internal seed.
- */
- public SimpleRandom() {
- while (value == 0) {
- value = (int) System.currentTimeMillis() ^ ZERO_SEED_REPLACEMENT;
- }
- }
- /**
- * Seeds the random number generator.
- */
- public SimpleRandom(int seed) {
- seed(seed);
- }
- /**
- * Seed the random number generator with the user argument.
- */
- public void seed(int seed) {
- value = seed;
- resetSeed();
- }
- /*
- * Get a pseudo-random number from the random algorithm.
- */
- public int generate() {
- /* do the magic seed calculation */
- value = (MAGIC_A * (value % MAGIC_QUOTIENT)) - (MAGIC_REMAINDER * (value / MAGIC_QUOTIENT));
- resetSeed();
- return value;
- }
- /*
- * Get a pseudo-random number from the random algorithm with values between 0 and (maxValue-1).
- */
- public int generate(int maxValue) {
- if (maxValue == 0) {
- return 0;
- } else {
- return generate() % maxValue;
- }
- }
- private void resetSeed() {
- if (value < 0) {
- value += MERSENNE_PRIME;
- } else if (value == 0) {
- value = ZERO_SEED_REPLACEMENT;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement