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 ??
Mathematically the numbers will not gain anything by rounding up or down in the last step. Instead the first and the last number have a 50% lower chance to get picked over all the other numbers.
Stick with CrazyCasta's or J.A's solution.
I wonder why other answers all use the int cast to generate the random number. Why not generate random integer directly, which is more accurate than real number way?
If you want to include randomness in the direction as well use random number for the same.
To do so you need to generate a second pseudo-random number to add or substract 1