简体   繁体   中英

Javascript - Math.random in a for loop

Just ran into a something interesting in Javascript while experimenting with generating a random number in the condition (is that what it's called?) of a for loop.

So, if I were to write the code like this:

for (var i = 0; i < 20; i++) {
    var count = 0;
    for (var j = 0; j < Math.floor(Math.random() * 20); j++) {
        count++;
    }
    console.log(count);
}

It would return a result like this:

9
5
8
3
3
2
6
8
4
4
5
6
3
3
5
3
4
5
3
11

But if I were to generate a random number in a variable before the second for loop:

for (var i = 0; i < 20; i++) {
    var count = 0;
    var loopEnd = Math.floor(Math.random() * 20 + 1);
    for (var j = 0; j < loopEnd; j++) {
        count++;
    }
    console.log(count);
}

It would return a result like this:

11
13
14
2
19
19
17
19
2
18
5
15
18
2
1
19
16
15
13
20

What exactly is happening here? It had me confused for a little while. Is the Math.random() inside the for loop generating a new random number after each iteration? Does the loop run the code, iterate, and check the condition, and generate a new random number each time it is checking the condition? Is this what is happening and is this why the numbers in the console are smaller than if I use Math.random() in a variable before the for loop?

In the first example's inner loop:

...
for (var j = 0; j < Math.floor(Math.random() * 20); j++) {
    count++;
}
...

the termination condition j < Math.floor(Math.random() * 20) is evaluated each iteration of the loop, and so the termination value is changing each iteration with the call to Math.random() making it more likely that the loop will terminate earlier.

As for the loop terminating earlier on average when the random number is chosen anew every iteration:

Without getting into proper statistical analysis, consider this simple train of thought:

How likely are you to get ten or more iterations?

If you draw just one random number between 1 and 20, you'll get 10 or more about 50% of the time.

If you get ten random numbers you need to have each of them higher than first 1, then 2, then 3 and so on, and the odds are reduced: 95% * 90% * 85% * ... * 50%.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM