Generating an Odd Random Number between a given Ra

2019-02-09 15:08发布

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

标签: java math random
10条回答
2楼-- · 2019-02-09 15:38

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.

查看更多
▲ chillily
3楼-- · 2019-02-09 15:39

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?

Random rn = new Random();
if(maximum % 2 == 1) maximum = maximum + 1; // turn right bound to even
if(minimum % 2 == 0) minimum = minimum - 1; // turn left bound to odd
int range = (maximum - minimum + 1) / 2;
int randomNum =  rn.nextInt(range) * 2 + minimum;
查看更多
家丑人穷心不美
4楼-- · 2019-02-09 15:42

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;  
  }
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-02-09 15:48

To do so you need to generate a second pseudo-random number to add or substract 1

Random_No = Min + (int)(Math.Random()*((Max-Min)+1))
repartitionNumber =(int)(Math.Random()*((2)) // between 0 and 1
if(Random_No%2 ==0)
{
      if(Random_No+1<=Max && Random_No-1>=Min)
      {
          if(repartitionNumber==0)
              Random_No = Random_No + 1; 
          else
              Random_No = Random_No - 1;  
      }
      else if(Random_No+1<=Max)
          Random_No = Random_No + 1;
      else if (Random_No-1>=Min)
          Random_No = Random_No - 1;
}
查看更多
登录 后发表回答