【问题标题】:Generate a random even number inside a range?在一个范围内生成一个随机偶数?
【发布时间】:2015-11-23 12:08:44
【问题描述】:

这是我遵循的格式:

 int randomNum = rand.nextInt((max - min) + 1) + min;

这是我的代码。我正在尝试获得 1 到 100 之间的随机偶数:

 Random rand = new Random(); 
 int randomNum = rand.nextInt((100 - 2) + 1) + 2;

我看到一种解决方案是将数字乘以 2,但这超出了预期范围。

我想过做一堆 if 语句来解决这个问题,但它似乎过于复杂。有没有比较简单的解决办法?

【问题讨论】:

  • 简单:生成一个超过一半范围的随机数,然后乘以2。
  • 哦!聪明的。 =) 我认为这应该可行。谢谢!
  • @Jesper 但是无法生成该范围内的第一季度偶数。
  • @rajuGT 你是什么意思?所有 3 个答案对我来说都是有效的。
  • 给定范围是从 2 到 100。建议的解决方案是在一半范围内生成一个随机数。即 2 到 49。在此可能的最低值可以是 2。然后将其乘以 2。即 4。所以在这里,我们不能在这里生成随机数 2。让我知道我的理解是否不正确或与大家不符。 (也考虑到随机范围),抱歉,这不应该是我之前评论中的第一季度。

标签: java random range


【解决方案1】:

只需生成一个从 0 到 49 的数字,然后将其乘以 2。

Random rand = new Random(); 
int randomNum = rand.nextInt(100/2) *2;

要在某个范围内执行此操作,只需将范围添加到:

int randomNum = startOfRange+rand.nextInt((endOfRange-startOfRange)/2) *2;

注意startOfRange应该是偶数或者转换成偶数。

【讨论】:

    【解决方案2】:

    这是一个关于如何做的小例子

    static Random rand = new Random();
    
    public static void main(String[] args) {
        for(int i = 0;i<100;++i)
            System.out.println(generateEvenNumber(0, 100));
    
    }
    
    private static int generateEvenNumber(int min, int max) {
        min = min % 2 == 1 ? min + 1 : min; // If min is odd, add one to make sure the integer division can´t create a number smaller min;
        max = max % 2 == 1 ? max - 1 : max; // If max is odd, subtract one to make sure the integer division can´t create a number greater max;
        int randomNum = ((rand.nextInt((max-min))+min)+1)/2; // Divide both by 2 to ensure the range
        return randomNum *2; // multiply by 2 to make the number even
    }
    

    【讨论】:

      【解决方案3】:

      在 Java 1.7 或更高版本中,我会使用 ThreadLocalRandom:

      import java.util.concurrent.ThreadLocalRandom;
      
      // Get even random number within range [min, max]
      // Start with an even minimum and add random even number from the remaining range
      public static int randEvenInt(int min, int max) {
          if (min % 2 != 0) ++min;
          return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
      }
      
      // Get odd random number within range [min, max]
      // Start with an odd minimum and add random even number from the remaining range
      public static int randOddInt(int min, int max) {
          if (min % 2 == 0) ++min;
          return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
      }
      

      here 解释了使用 ThreadLocalRandom 的原因。另请注意,我们对 ThreadLocalRandom.nextInt() 的输入 +1 的原因是确保最大值包含在范围内。

      【讨论】:

        【解决方案4】:

        在你得到1和100之间的随机数并乘以2后,你可以得到number % 100。比如:

        int random = rand.nextInt(100);
        random = (random * 2) % 100;
        

        这样number 将始终小于100 甚至。

        【讨论】:

          【解决方案5】:

          另一种方法(可能不是最佳方法):

          1. 创建一个包含 1 到 1 之间所有偶数的数组(或列表) 100.(这很容易用循环)
          2. 当您需要一个随机偶数时,只需从该数组或列表中获取一个随机数(使用带有长度或大小的随机数)。

          【讨论】:

          • 这效率极低。您可以证明这一点的唯一方法是,如果有一些复杂的数学可以计算出合格的数字(例如仅质数),或者您想确保没有数字重复(通过删除它们)
          • @TimB 我同意这不是最有效的,也不是我的选择(你的更清晰和优雅),但正如我所测试的那样,它似乎并不是那么无能。假设列表已经初始化,您的代码在生成 1000000 个数字时需要大约 14 毫秒,而我的代码需要大约 15 毫秒(在我的机器中)。
          • 这不是一个糟糕的解决方案 - 它会起作用,并且在某些情况下是唯一的方法(如我的第一条评论中所述)。但是,正如您自己所说,只要列表已初始化,这意味着始终从同一范围中进行选择。还有内存性能下降和更多的缓存时间丢失,而且范围越大,成本就越差。基本上这是一个缩放性较差的解决方案。
          【解决方案6】:
          private int getRandomNoOdd(int maxValue) {//min value is 0, including zero, max value can potentially be reached by randomness
              int random = 0;
              while (true) {
                  random = (int) (Math.random() * (maxValue + 1));
                  if (random % 2 != 0)
                      continue;
                  break;
              }
              return random;
          }
          

          【讨论】:

            【解决方案7】:

            生成 2 到 1000 之间偶数随机数的最佳方法

            Random random = new Random();
                    int Low = 2;
                    int High = 1000;
                    int randomNumber = random.nextInt(High-Low) + Low;
                    if(randomNumber % 2 != 0){
                        randomNumber = randomNumber + 1;
                    }
            

            https://www.google.com/search?q=sim+phone+details

            【讨论】:

              【解决方案8】:

              你也可以从一个范围内得到一个随机数,然后,如果 % 2 != 0,加 1。

              【讨论】:

                猜你喜欢
                • 2018-04-08
                • 2011-08-02
                • 1970-01-01
                • 1970-01-01
                • 2019-10-30
                • 2021-04-05
                • 2011-05-16
                • 2014-05-15
                • 2014-05-18
                相关资源
                最近更新 更多