【发布时间】:2018-11-11 00:47:47
【问题描述】:
假设我想用一堆不重复的随机数填充一个数组。要求是,您必须使用来自 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.
}
}
}
【问题讨论】: