When using a random parameter in a loop comparison, does it call the randomization function once or every time the loop is executed?

According to 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 } 

Is k rand.nextInt(10) compared to rand.nextInt(10) only once, when the cycle starts to work, so that there is an equal probability that the cycle will work with every interval between 0 and 9? Or does he compare each iteration of the loop, making lower numbers more likely?

Also, is it different between languages? My example is for Java, but is there a standard that exists between most languages?

+6
source share
2 answers

Can k be compared with rand.nextInt (10) only once when the loop starts to work?

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

If you want to create a random number once, define a variable and set it before nextInt(10) before the loop. You can also use an alternative that takes into account the flip side:

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

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

+4
source

Let 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

 testIt() 0 testIt() 1 testIt() 

Answer: it is compared at each iteration of the loop, which makes it more likely for lower numbers.

It may differ in other languages. Even if it is not today, it may be tomorrow. If you want to know, you should check it out.

Edit

For example, in Java 8 you can 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)); } 
+1
source

Source: https://habr.com/ru/post/973332/


All Articles