How to generate an odd Random number between a given range..
For Eg: For range between 1 to 6 .. Random No is 3 or 1 or 5
Method for Generating Random No :
Random_No = Min + (int)(Math.Random()*((Max-Min)+1))
Refer How do I generate random integers within a specific range in Java?
Method For Generating Odd Random No :
Random_No = Min + (int)(Math.Random()*((Max-Min)+1))
if(Random_No%2 ==0)
{
if((Max%2)==0)&&Random_No==Max)
{
Random_No = Random_No - 1;
}
else{
Random_No = Random_No +1;
}
}
This Function will always convert 2 into 3 and not 1 Can we make this a more random function which can convert 2 sometimes into 3 and sometimes into 1 ??
Assuming max is inclusive, I'd suggest the following:
if (Max % 2 == 0) --Max;
if (Min % 2 == 0) ++Min;
Random_No = Min + 2*(int)(Math.random()*((Max-Min)/2+1));
It results in even distribution among all the odd numbers.
If you want to include randomness in the direction as well use random number for the same.
int randomDirection = Min + (int)(Math.Random()*((Max-Min)+1));
if(randomDirection%2==0) { // any condition to switch the direction
Random_No = Random_No + 1;
} else {
Random_No = Random_No - 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With