sanchop22 sanchop22 - 2 months ago 14
C Question

Exact C equivalent of Java Random.nextInt(int bound) method

I am working on a project that I port some Java code into C. Everything has gone well until now but I'm stucked at porting Random.nextInt(int bound) method into C.

My Java code is:

int arr[] = new int[100000];
Random r = new Random(0);
for (int i = 0; i < 100000; i++)
arr[i] = r.nextInt(20);


where arr array has always the same contents (after each execution) which is normal.

My equivalent C code is:

int arr[100000], i;

srand(0);
for (i = 0; i < 100000: i++)
arr[i] = rand() % 20;


The contents of two arr arrays are not same.

I thought to print the generated random numbers to a file in Java code in order to use them (the numbers) as a constant array in C code instead of using rand() function but the size of the array will be so huge which will prevent me to do this because the C code will work on an embedded device (microcontroller).

My question is how can I port that Java code into C where I can obtain the same random numbers?

Answer Source

Java JDK sources are publicly available.

If you want an exact equivalent of Java's random number generator in C, go grab the sources and write/port it yourself.