0

我有这个数组

int [] marc = new int[4];

我需要在1-10它的范围内插入一组不重复的随机数

我正在使用这个 for 循环来设置随机数

for (he = 0; he < 4; he++) {
    marc[he] = rn.nextInt(10 - 1 + 1) + 1;
    marc[he]++; 
}

它给了我随机数,但在数组中重复了

我也在用

java.util.Random;
4

2 回答 2

1

当您的范围较小时,使用java.util.Random;将更频繁地生成重复数字,在您的情况下仅为 10。您的代码中没有条件检查生成的随机数是否已存在于您的数组中。

在将生成的数字插入数组之前,您首先需要检查该数字是否已存在于您的数组中。如果没有,则将该数字插入数组中,否则生成下一个随机数。

于 2017-01-09T18:53:57.257 回答
1

嗯,是的,数字可以在随机的同时重复。您需要执行自己的逻辑来验证它们是否已经在阵列上,这可以通过以下代码完成:

在代码中,我使用了一个包含 10 个元素的数组来观察即使在这种情况下也没有重复的数字。

import java.util.Random;

public class RandomNumbersNoRepeating {
    public static void main(String[] args) {
        int array[] = new int[10];
        Random random = new Random();

        //Fills the array
        for (int i = 0; i < array.length; i++) {
            boolean found = false;
            int r = 0;
            do {
                found = false;
                r = random.nextInt(10) + 1;
                //Here we check if the number is not on the array yet
                for (int j = 0; j < array.length; j++) {
                    if (array[j] == r) {
                        found = true;
                        break;
                    }
                }
            } while (found);

            array[i] = r;
        }

        //Prints the array
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }
}

另一种可能的解决方案,如评论中给出的,可能是将数组从 1-10 随机排列,并获得前四个数字

于 2017-01-09T19:11:29.670 回答