简体   繁体   中英

Simple deterministic method to generate an array of random numbers?

I am looking for a simple method to populate a large int[] testArray with data. Method should accept a single parameter to generate a deterministic sequence of integers, but look like noise at a first glance.

Something like this comes to mind, but data might have patterns.

public int[] populate(int arraySize, int somePrime){
int[] testArray = new int[arraySize];
int offset = -100000; 
long fib = 0; long fibm1 = 1; long fibm2 = 1; 
//...
for(int i = offset; i< testArray.length; i++){
    fib= fibm1+ fibm2;
    fibm2= fibm1;
    fibm1= fib;
    if(i >= 0){  testArray[i] = (int) fib%somePrime; }
    }

return testArray[i];
}

What would be a better method?

You can do this by initializing a random number generator with a fixed seed. The sequence it generates will look random to someone who doesn't know the seed, but you will be able to reconstruct the sequence by using the same seed again.

For example:

Random r = new Random(mySeed);
int[] testArray = new int[arraySize];
for(int i=0; i<arraySize; i++) {
    testArray[i] = r.nextInt();
}

Update: This method is susceptible to someone guessing your seed by trial and error, especially if it's a small number or otherwise predictable. You could also store a secret, fixed seed and combine the two into a longer seed. But you should be careful about how you do this, as there are pitfalls. See Deterministically combine more than one source of entropy .

You could use SecureRandom . Then you could use your number to generate a seed:

int seed = 1234;
Random rand = new SecureRandom(SecureRandom.getSeed(seed));
int number = rand.nextInt();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM