3

In my program I need to produce many large sequences of random integers.

I know that I can just use the Random object to create the sequence, store that sequence in a list or an array and then query it for the i'th element when it needed but as the sequence can be very long (1M elements) and I have many different sequences I wish to know if I can store only the seed of each sequence and do something like:

public static int getIthNumber(int seed, int i){
    Random r = new Random(seed);
    for (int j=0; j< i-1; ++j) r.nextInt();
    return r.nextInt();
}

but without the overhead of the loop..

0

1 Answer 1

3

If you need random access you can avoid using a proper sequence.

public static int getIthNumber(int seed, int i){
    return new Random(seed * 10123457689L + i * 101111).nextInt();
}
Sign up to request clarification or add additional context in comments.

3 Comments

they are big primes from primes.utm.edu/curios Pick any you find amusing. ;) The product of the two prime you use must be larger than the longest possible sequence otherwise the sequences will over lap. Note: Random only uses 48-bit of the seed and will repeat after 2^^48 values.
Thanks again, can you please explain or point me to an explanation about the motivation to select two prime numbers p1 and p2 so that p1*p2 > maxseqlen as you proposed.
If you have two small primes e.g. 31 and 3, it means that after 93 (31 * 3) values from one it will have the same sequence as another. (There will also be another seed which is the same after 2 * 93 ... n * 93. In the extreme case if you just add seed + i seeds 1,2,3,4 will be same after 3,2,1,0 values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.