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 ??
Instead of generating a random number between 0 and 6, generate one between 0 and 5 and round up to the nearest odd number, that way you'll have a perfect distribution (33% for each possibility (1, 3, 5))
Let the rouding above or below depend on a random epsilon.
In Java 1.7 or later, I would use ThreadLocalRandom:
The reason to use ThreadLocalRandom is explained here. Also note that the reason we +1 to the input to ThreadLocalRandom.nextInt() is to make sure the max is included in the range.
Assuming max is inclusive, I'd suggest the following:
It results in even distribution among all the odd numbers.
To generate an odd number from a integer you can use
n * 2 + 1
Really you are generating random numbers and applying a transformation afterwardsThis will work even if the range is [1,5] [2,5] [2,6] [1,6]
How about checking the return from Math.random() as a floating number. If its int part is an even number, then convert up/down based on its floating part. Like:
assume Math.random() returned x.y; if x is even, return (y>=0.5)?(x+1):(x-1)
Will this randomized a little?