2

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.

2
  • That is two random generators, how can they be equal? Commented Jan 13, 2020 at 7:22
  • 1
    the range of the first one is [min, max], the second, [-min, max - min]. So, no. Commented Jan 13, 2020 at 7:50

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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. (i.e. 0,1,2,3,4)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.