How to find a Random Number Between two given Numbers
Suppose we want to generate a number between two given numbers X and Y then we can use the following two approaches.Approach 1
- Generate a random number between 0 to (Y - X ) just add this to X. i.e X+N
For, example if we have to calculate a random number between 100 and 150,
then in that case X = 100 , Y = 150,
Then we calculate a number between 0 to (150-100) i.e 0 to 50. Thus, we just need to add this to 100 to get a number in range of 100 to 150.
Then we calculate a number between 0 to (150-100) i.e 0 to 50. Thus, we just need to add this to 100 to get a number in range of 100 to 150.
Approach 2
- Generate a number N using the Math.random() method such that ( N < X< Y )
- If N <= Y - X then result is X+N
- else, we add the difference of N from the difference of X and Y i.e X + ( N - ( Y - X ))
For, example if we have to calculate a random number between 100 and 150,
then in that case X = 100 , Y = 150,
- Case 1 : N = 24 ( less than Y- X)
In this case result will be X + N that is 24 + 100 = 124 - Case 2 : N = 88 ( greater than Y-X )
In this case result will be X + ( N - (Y - X)) that is 100 + (88 - (100 - 50)) = 138
package com.ekiras.demo;
public class Rand {
public static void main(String args[]){
System.out.println(sol1(100,150));
System.out.println(sol2(100,150));
}
public static int sol1(int start, int end){
int num = rand(end-start);
return num+start;
}
public static int sol2(int start,int end){
int num = rand(start);
if(num<=end-start)
return num+start;
else{
return start+num-(end-start);
}
}
public static int rand(int n){
return ((int)(Math.random()*n));
}
}
133
145
Comments
Post a Comment