Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating an Odd Random Number between a given Range

Tags:

java

random

math

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 ??

like image 685
Sanket Avatar asked Sep 26 '12 05:09

Sanket


2 Answers

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.

like image 107
CrazyCasta Avatar answered Oct 16 '22 11:10

CrazyCasta


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;  
  }
like image 45
Bharat Sinha Avatar answered Oct 16 '22 09:10

Bharat Sinha