Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using a random parameter in a loop's qualifying comparison, does it call the randomization function once or each time the loops runs?

As per the question, let's say you have the following code:

    Random rand = new Random();
    for (int k = 0; k < rand.nextInt(10); k++) {
        //Do stuff here
    }

Does k get compared to rand.nextInt(10) only once, when the loop starts running, so that there's an equal chance of the loop running at every interval between 0 and 9? Or does it get compared each iteration of the loop, making it more likely for lower numbers to occur?

Furthermore, does this differ between languages? My example is for Java, but is there a standard that exists between most languages?

like image 688
Kyton Avatar asked Aug 04 '14 17:08

Kyton


2 Answers

Does k get compared to rand.nextInt(10) only once, when the loop starts running?

No, k is compared to the next random number the rand generates each time the loop continuation condition is checked.

If you wish to generate a random number once, define a variable, and set it to nextInt(10) before the loop. You could also use an alternative that counts backwards:

for (int k = rand.nextInt(10); k >= 0 ; k--) {
    //Do stuff here
}

The same is true in at least four other languages which use this syntax of the for loop - C++, C, C#, and Objective C.

like image 170
Sergey Kalinichenko Avatar answered Sep 20 '22 07:09

Sergey Kalinichenko


Let's testIt()

public static int testIt() {
  System.out.println("testIt()");
  return 2;
}
public static void main(String[] args) {
  for (int i = 0; i < testIt(); i++) {
    System.out.println(i);
  }
}

Output is

testIt()
0
testIt()
1
testIt()

The answer is it gets compared at each iteration of the loop, making it more likely for lower numbers to occur.

It might vary in other languages. Even if it doesn't today, it might tomorrow. If you want to know, you should test it.

Edit

For example, in Java 8 you could write

import static java.util.stream.IntStream.rangeClosed;
// ...

public static void main(String[] args) {
  Random rand = new Random();
  rangeClosed(1,1+rand.nextInt(10)).forEach(n -> System.out.println(n));
}
like image 43
Elliott Frisch Avatar answered Sep 22 '22 07:09

Elliott Frisch