Advertisement
Guest User

Untitled

a guest
Jan 20th, 2018
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.28 KB | None | 0 0
  1.    static int randomInRange(int num1, int num2)
  2.     {
  3.         if(num1<num2)
  4.         //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
  5.             return 0;
  6.         else
  7.  
  8.         {
  9.             int randomNum = generator.nextInt((num1 - num2) + 1) + num2;
  10.             //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
  11.             //To do this the key is understanding the math on how the random class generates numbers.
  12.             //As a general rule to base it off of, generator.nextInt(5); will generate a number from 0 to 4
  13.             //If you instead changed the line to say generator.nextInt(5)+1; it would generate a number from 1 to 5
  14.             //So it generates from 0 to whatever you pass into the method in the parentheses, the addition or subtraction is applied after the generation.
  15.             //
  16.             //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.
  17.             //So we need to pre-define that the added amount from num2 is not going to be part of our generation.
  18.             //
  19.             //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.
  20.             //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;
  21.             //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.
  22.             //So because our index starts at 0 for the generation what we need is what I wrote, generator.nextInt((num1-num2)+1)+num2;
  23.             //This properly establishes our bounds for the generation of a random number in a range defined by two variables.
  24.             //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.
  25.             return randomNum;
  26.         }
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement