-5

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?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
sanchop22
  • 2,729
  • 12
  • 43
  • 66
  • Trying to port code exactly from one language to another with different abstraction capabilities typically results in chaos, unmaintainable code and a hell of problems. Siad that: we are not a coding service. – too honest for this site Jul 17 '17 at 14:17
  • If this is supposed to be an array of random numbers, why is it important to have the same numbers? – Henry Jul 17 '17 at 14:18
  • Great! So it is really random! (If the implementation of the random number generator in different languages is different, then they behave differently and generate different sequences of random numbers.) So this you can't make equivalent between Java and C. – Paul Ogilvie Jul 17 '17 at 14:19
  • 1
    `How can I port that Java code into C where I can obtain the same random numbers?` - Simple - Find out which random number generator is implemented in Java. Implement it in C and start it with the same seed. However hardcoding them would be way easier if you don't want them to be random. – muXXmit2X Jul 17 '17 at 14:20
  • Not only will the generated random number sequence differ between JAva and your C library, they will almost certainly differ too between your PC C compiler and your embedded system's C cross compiler. http://dilbert.com/strip/2001-10-25 – Clifford Jul 17 '17 at 18:09

2 Answers2

1

The Java Random class and rand in C use two different psuedorandom number generators. You will not be able to reproduce the exact same random numbers with C that you did with Java.

The way you are writing your application you shoud avoid depending on having the exact same random numbers.

0

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.

mfro
  • 3,286
  • 1
  • 19
  • 28