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?
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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With