简体   繁体   中英

Generate random number in range(java)

To generate a random number in a given range, we can write:

Random().nextInt((max - min) + 1) + min .

I would like to know that is it equal to Random().nextInt(max + 1) - min OR not.

It's not, just check the edge cases. For min = 5 and max = 10

max - min + 1 = 6 , so nextInt((max - min) + 1) results in minRand = 0 to maxRand = 5 . Add min and you get a number between 5 and 10.

max + 1 = 11 , so nextInt(max + 1) results in minRand = 0 to maxRand = 10 . Substract min and you get a number between -5 and 5.

It's not, but it seems not easy to explain.

(max - min) + 1 is the argument to nexInt method. It is the value from 0 to the total of elements in that range (from min to max) and then this range is moved to start at the minimum value.

In other words, nextInt((max - min) + 1) generates a random int from 0 to max-min . And adding min will result in a random integer from min to max .

The other expression is just wrong because from 0 to max + 1 doesn't get the range of values you want.

I would like to know that is it equal to Random().nextInt(max + 1) - min OR not.

Definitely not the same. You can sub in 2 numbers for max and min . You will see their differences.

Let your min be 7 and max be 9 :

Random().nextInt((max - min) + 1) + min
// Random().nextInt((9 - 7) + 1) + 7
// Random().nextInt(3) + 7
// Randomly generates (0, 1, 2) + 7
// Randomly generates (7, 8, 9)

Now swap 7 and 9 into the other code snippet:

Random().nextInt(9 + 1) - 7
// Random().nextInt(10) - 7
// Randomly generates (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) - 7
// Randomly generates (-7, -6, -5, -4, -3, -2, -1, 0, 1, 2)

One way for me to interpret how random.nextInt(val) works is by looking at the value of val . Let say if the final evaluation of val is 5. There are 5 possibilities to be randomly generated starting from 0. (ie 0,1,2,3,4)

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