Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generating random sequence of numbers with random access to the sequence elements

Tags:

java

random

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..

like image 962
bennyl Avatar asked Jul 18 '26 14:07

bennyl


1 Answers

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();
}
like image 68
Peter Lawrey Avatar answered Jul 21 '26 03:07

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!