【问题标题】:How to prevent a value from being generated in a random int? (Java)如何防止在随机 int 中生成值? (爪哇)
【发布时间】:2016-11-19 21:49:46
【问题描述】:

我有两个随机生成的变量。 LoadG4 输出到一个按钮,其他 3 个按钮具有不同的随机值 1 生成。我的目的是确保随机生成的 randoms1 的任何值都不等于 LoadG4。例如,如果范围在 0 到 9 之间且 LoadG4 最终为 3,则 randoms1.nextint... 中的其他随机数不得为 3。例如,它们可以是 7、4 或 5,但与加载G4。

这是我的代码:

Random GenerateG4 = new Random();
            int loadG4 = GenerateG4.nextInt(10);
            Random randoms1 = new Random();
            final TextView number = (TextView) findViewById(R.id.number);
            number.setText(""+loadG4);
            for(int allrbA=0; allrbA<4; allrbA++) {
                selectrb[allrbA].setText(""+randoms1.nextInt(10));
            }
            selectrb[rbselector].setText(""+loadG4);

我该怎么做?

非常感谢。

更新代码:

if (rbvalue==loadG4) {
                    int realrbvalue = rbvalue++;
                    selectrb[allrbA].setText(""+realrbvalue);
                }
                else {
                    selectrb[allrbA].setText(""+rbvalue);
                }
            }

为什么还是不行?

【问题讨论】:

  • 生成一个 0-8 范围内的数字,如果该数字大于或等于您要避免的数字,则加 1。
  • 3 只是一个例子,这对我来说没有多大意义。这将如何运作?
  • @AndyTurner 请查看更新后的代码。为什么这不起作用?

标签: java android random


【解决方案1】:

以下内容应该让您走上正轨。这个想法是,对于第二次提取,我们将范围缩小一。如果提取的数量小于之前提取的数量,那很好。如果不是,那么我们给它加 1 得到一个在 [v1+1, n] 范围内的数:

Random r = new Random();
int v1 = r.nextInt(n);
int  v2 = r.nextInt(n-1);
if (v2 >= v1)
  v2++

【讨论】:

  • 所以我必须手动重复每个按钮的代码并将每个值设置为每个按钮?不是理想的解决方案。
【解决方案2】:

评论的变体:

for(int allrbA=0; allrbA<4; allrbA++) {
   int r = randoms1.nextInt(10 - 1); // range one less because one will be skipped
   if (r == load4G) r = 9;           // don't want this one, take the one
                                     // that would have been included in the full range

   selectrb[allrbA].setText("" + r);
}

评论建议是为r &gt;= load4G 的任何随机值添加一个到r - 这意味着r 的最终值永远不会等于load4G - 具有相同的净效果。

用循环重新生成一个新的随机数:

for(int allrbA=0; allrbA<4; allrbA++) {
   int r; 
   do {
      r = randoms1.nextInt(10);   // get a random number
   } while (r == load4G);         // until it is different

   selectrb[allrbA].setText("" + r);
}

如果所有随机数必须不同,(Fisher-Yates)洗牌将是一个合适的解决方案。

【讨论】:

  • r = randoms1.nextInt(10 - 1); 是什么意思那是为了什么?
  • nextInt(10 - 9) 返回 [0, 9) 范围内的随机数 - 例如。值为 0..1..7..8.
  • 为什么不只是 r = randoms1.nextInt(10 ); ?
  • 因为这会返回一个 [0, 10) 范围内的数字 - 例如。值为 0..1....9..10。然而,这没有留下“空间”来处理跳过 load4G。请注意,使用循环的方法不需要考虑这一点,因为它会尝试获取新的随机数。
  • 我不明白 if (r == load4G) r = 9;要么,为什么设置它等于 9?
【解决方案3】:

创建一个数组并检查您的数组中是否已经存在新的随机数。虽然您只有 4 个步骤的循环,但它不会影响性能,但在此解决方案中,所有数字都是随机的。

    int arr[] = new int[4];

    for(int allrbA=0; allrbA<4; allrbA++) {

        int num;

        do{
             num = randoms1.nextInt(10);
        }
        while(!Arrays.asList(arr).contains(num));

        arr[allrbA] = num;

    }

【讨论】:

  • 使所有随机数唯一 - 即。在洗牌或键盘键时 - 考虑(Fisher-Yates)洗牌。
猜你喜欢
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
  • 2011-12-29
  • 1970-01-01
  • 1970-01-01
  • 2014-01-01
  • 1970-01-01
相关资源
最近更新 更多