-2

Can you help me to understand what is the meaning of these randomization?

I have found it in a c code that I have to translate, it return always 41:

int main(){
  srand(1);
  printf("\n%d",rand());
}

How I can emulate the srand(1) and rand() in Java?

michele
  • 26,348
  • 30
  • 111
  • 168
  • I think that it is happening because `srand()` should be a "random" number, usually use `time()` – Evan Carslake Jul 23 '15 at 22:01
  • No, it doesn't. In my system it always produces 1804289383. – Am_I_Helpful Jul 23 '15 at 22:01
  • 1
    How familiar are you with pseudo-random number generation? – rabbit Jul 23 '15 at 22:01
  • System.out.println("41"); –  Jul 23 '15 at 22:02
  • @michele-Solution to your problem is this answer ---> http://stackoverflow.com/a/12458415/3482140 – Am_I_Helpful Jul 23 '15 at 22:06
  • 1
    Actually, that doesn't help him at all. If you want the same result as the C code, you'll have to reimplement the same RNG. Java's RNG is different, as are other C compilers'. BUT, I strongly suspect what you are actually trying to accomplish is different...so back up a step, give us a better view: what are you trying to accomplish? – Lee Daniel Crocker Jul 23 '15 at 22:09
  • here you can find implementation of srand() and rand() -->http://stackoverflow.com/questions/4768180/rand-implementation?answertab=active#tab-top – Alon Jul 23 '15 at 22:09

1 Answers1

1

My answer assumes that you just want to emulate the behavior of srand() and rand(), but do not care about the '41' you say that you always get.

This is basically just the idea of pseudo-random number generation. If you set the seed to a constant value (1 in this case), then call the random() function, it will always return the same value. This is because it is basically saying "set the index to 1 in the big list of 'random' numbers" so that the next time I call random it returns the n-th value in that 'list'. In reality, it is a bit more complex, but that's how I like to think about it sometimes. To emulate the behavior of your code in Java, you can try the following:

public static void main(String[] args) {
    Random rand = new Random(1);

    System.out.println(String.valueOf(rand.nextInt()));
}
rabbit
  • 1,476
  • 12
  • 16
  • it returns only big negative number...in c the same return positive number...why? – michele Jul 23 '15 at 22:58
  • This goes back to Lee Daniel Crocker's comment on the OP -- There are different ways/algorithms to generate random numbers, and Java & C use different approaches. – rabbit Jul 24 '15 at 18:05
  • If you're interested there is a list of a few (maybe all, I'm not sure) PRNGs on Wikipedia [here](https://en.wikipedia.org/wiki/List_of_random_number_generators). – rabbit Jul 24 '15 at 18:08