【问题标题】:In the given example, what is the logic behind the use of the Random class?在给定的示例中,使用 Random 类背后的逻辑是什么?
【发布时间】:2020-04-04 10:37:11
【问题描述】:

下面的方法创建一个给定大小的 int 类型的一维数组,并将值 1 随机分配给数组的给定百分比。我不完全理解这个例子中 nextInt 的使用。如何确保在 while 循环的每次迭代中选择不同的索引,而不是在前一次迭代中已经选择的索引。

import java.util.Random;

...

    int[] randomIntArray(int size, double percent) {
        int n = (int) (size * percent);
        int[] array = new int[size];
        Random r = new Random();

        while(n > 0) {
            int next = r.nextInt(size);
            if (array[next] != 0) continue;
            array[next] = 1;
            n--;
        }

        return array;
    }

【问题讨论】:

    标签: java arrays class random


    【解决方案1】:

    if (array[next] != 0) continue; 行清楚地表明(尽可能清晰地格式化代码),如果数组索引的值已经设置为 1,则直接返回 while 循环的头部。

    continue 关键字应谨慎使用,并且应谨慎使用,因为它对读者不太友好,而且通常有更好的方法来实现相同的目标。..

    【讨论】:

    • 所以它会在递减之前回到while循环的头部?
    【解决方案2】:

    如果之前选择了next,这很好,因为有一个if (array[next] != 0) 检查,然后是array[next] = 1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 2017-10-17
      • 1970-01-01
      • 2022-01-12
      • 2018-06-18
      • 2020-05-22
      相关资源
      最近更新 更多