【问题标题】:Filling an array with random numbers from the range [-n, n] using Math.random使用 Math.random 用 [-n, n] 范围内的随机数填充数组
【发布时间】:2019-02-11 13:45:23
【问题描述】:

我有一个函数,可以在其中输入多维数组 n 的大小。接下来,我用 [-n, n] 范围内的随机数填充这个数组,使用 Math.random():

private int[][] enterMatrixSize() {
    System.out.print("enter matrix size (n): ");
    String input;
    while (!(input = in.next()).matches("\\p{Digit}+")) {
        System.out.print("Please enter a positive Integer: ");
    }
    int size = Integer.parseInt(input);
    int[][] array = new int[size][size];
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++) {
            array[i][j] = (int) (Math.round(Math.random() * (size + 1)) - size / 2);
        }
    }
    for (int i = 0; i < array.length; i++, System.out.println()) {
        for (int j = 0; j < array[i].length; j++) {
            System.out.print(array[i][j]+" ");
        }
    }
    return array;
}

但它显示了一些不正确的值。例如,当我输入 n 等于 1 时 - 显示数字 0、1 和 2。这很奇怪。因为应该输出 -1, 0, 1

【问题讨论】:

  • size + 1 替换为size 否则将随机数上移@98​​7654324@,这就是您获得当前输出的原因
  • 因为 1.5 轮是 2,所以换句话说,假设 random()=1 和 size=1 那么你有 1*(1+1))-1/2 所以 (2-1) /2,改为使用 .floor(x) 方法
  • @vmrvector 然后Math.floor() 可以完全省略,转换为int 将已经丢弃所有小数位,这与地板操作相同
  • @Lino 不适用于负数。 Math.floor(-1.5) == -2,而(int)(-1.5) == -1
  • @DodgyCodeException 您完全正确,我的评论甚至指出:... 将丢弃所有小数位...,因此必须使用负数 Math.floor()用过的。虽然如果你已经可以使用 jdk 来解决这个问题,为什么还要提出这样的逻辑 ThreadLocalRandom#nextInt(int, int) :)

标签: java arrays random


【解决方案1】:

我会改变这一行:

array[i][j] = (int) (Math.round(Math.random() * (size + 1)) - size / 2); 

到:

array[i][j] = ThreadLocalRandom.current().nextInt( -size, size + 1);

生成一个特定范围内的随机int值,这里是[-size, size]

【讨论】:

  • 嗯,我们有同样的想法,但你的速度快了几秒钟,然后投个赞成票;)
【解决方案2】:

我建议使用ThreadLocalRandom,它提供了一种方便的方法:nextInt(int origin, int bound)。然后可以像这样在你的循环中使用它:

int[][] array = new int[size][size];
ThreadLocalRandom r = ThreadLocalRandom.current();
for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array[i].length; j++) {
        array[i][j] = r.nextInt(-size, size + 1);
    }
}

第一个参数origin 定义数字应该从哪里开始,第二个参数bound 将生成的数字限制为唯一的给定值。

【讨论】:

  • 已经赞成你的答案,因为你添加了一些解释;)
【解决方案3】:

因为 1.5 轮是 2,所以换句话说,假设 random()=1 和 size=1 那么你有 1*(1+1))-1/2 所以 (2-1)/2

round(1.5)=2

改为使用 .floor(x) 方法或不使用round,因为您已转换为int,这也应该有效(正如@Lino 指出的那样)。

总结1.5的四舍五入结果是2, 使用 floor 这样你就有 1 个。

【讨论】:

    猜你喜欢
    • 2016-07-01
    • 2011-10-28
    • 2021-06-20
    • 2020-07-16
    • 1970-01-01
    • 2018-12-25
    • 2019-03-30
    • 2016-05-31
    • 1970-01-01
    相关资源
    最近更新 更多