2

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?

Imran
  • 12,950
  • 8
  • 64
  • 79
Stepan
  • 1,391
  • 18
  • 40
  • A review of generators and features is e.g. https://archive.org/details/arxiv-1005.4117 – Davide Fiocco Feb 18 '18 at 21:51
  • google pseudo random generators .... you just code your own deterministic one like this [avr code not working i want to generate random numbers help please](https://stackoverflow.com/a/29296619/2521214) ... or use any bigint sequence/recurrence modulo prime ... – Spektre Feb 19 '18 at 08:17

2 Answers2

6

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.

Imran
  • 12,950
  • 8
  • 64
  • 79
1

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();
Christian
  • 22,585
  • 9
  • 80
  • 106