假设我想用一堆不重复的随机数填充一个数组。要求是,您必须使用java.util.Random中的Random类,不能使用ArrayList (我已经使用Collections.shuffle做到了。您只能使用一维数组和任何类型的循环(包括if语句)。为了解决这个问题,我做了一个225的数组,随机数不允许超过225。这是我想出的解决方案,但它似乎不是很有效。我怎样才能更快地做到这一点?
我用从1到225的随机数填充了数组。我将数组中的每个元素与其他每个元素进行比较,如果有一个相似之处,我将从0元素重新开始比较。我在下面包含了我的源代码。
    int [] value = new int[225]; 
    int randnum;
    Random num = new Random();
    for (int x = 0; x < value.length; x++) // Fills array with Random Numbers from 0 to 225
    {
        randnum = (num.nextInt(225)) + 1;
        value[x] = randnum;
    }
    for (int y = 0; y < value.length; y++) // These two loops compare each value of the array
    {
        for (int z = y + 1; z < value.length; z++)
        {
            while (value[y] == value[z])
            {
                value[y] = num.nextInt(225) + 1;
                y = 0; // If the loop runs, the entire looping process starts over again.
            }
        }
    }https://stackoverflow.com/questions/50633894
复制相似问题