Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static int randomInRange(int num1, int num2)
- {
- if(num1<num2)
- //we need to check to make sure that num2 is the smaller number because we use it as a base for our random number generator, if it is not we return just 0
- return 0;
- else
- {
- int randomNum = generator.nextInt((num1 - num2) + 1) + num2;
- //So the goal is to take two numbers (num1 and num2 in this case) and generate a number that is one of them or between them
- //To do this the key is understanding the math on how the random class generates numbers.
- //As a general rule to base it off of, generator.nextInt(5); will generate a number from 0 to 4
- //If you instead changed the line to say generator.nextInt(5)+1; it would generate a number from 1 to 5
- //So it generates from 0 to whatever you pass into the method in the parentheses, the addition or subtraction is applied after the generation.
- //
- //What this means is that if we simply had generator.nextInt(num1)+num2; it would generate a number from 0 to num1 and THEN add num2 to the result.
- //So we need to pre-define that the added amount from num2 is not going to be part of our generation.
- //
- //generator.nextInt(num1-num2)+num2; is getting very close, what this does is generates a number from 0 to (num1-num2) and then adds num2 to make the base number correct.
- //but there is one issue with this still, as an example lets say num1 is 5 and num2 is 3, our method would run as generator.nextInt(5-3)+3;
- //This can be rethought of as generator.nextInt(2)+3; so it generates from 0-1 and THEN adds 3, this removes the possibility of it generating a 5, which we want to be possible.
- //So because our index starts at 0 for the generation what we need is what I wrote, generator.nextInt((num1-num2)+1)+num2;
- //This properly establishes our bounds for the generation of a random number in a range defined by two variables.
- //If we were to use the same example it would evaluate instead as generator.nextInt(3)+3;, which generates from 0-2 then adds 3, giving a possible range output of 3-5, what we want.
- return randomNum;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement