【发布时间】:2020-09-12 22:07:58
【问题描述】:
我需要创建一个程序,在 java 中创建从 0(incl) 到 10(excl) 的 10 个唯一数字,但到目前为止我的重复了一些数字。我可以实现的最佳方式是什么?
到目前为止的代码..... (原谅我的代码,我对java还是有点陌生)
public static int[] UniqueRand (int N)
{
//Create a list of random numbers
int [] randNums = new int[N];
Random numRandom = new Random();
for (int i = 0; i < N; i++){
randNums[i] = numRandom.nextInt(N);
}
return randNums;
}
主要功能: (通常 (n) 可以是任何范围,而不仅仅是 10)
public static void main(String [] args)
{
int n = 10;
Random newRandom = new Random();
int [] randNums = UniqueRand(n);
int [] replace = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println();
for (int i = 0; i < n; i++){
for (int j = i + 1; j < n; j++){
if (randNums[i] == randNums[j]){
for (int k = 0; k < 10; k++){
if (randNums[i] != replace[k]) randNums[i] = replace[k];
}
}
}
}
}
输出将是: [9, 1, 5, 9, 0, 2, 4, 6, 1, 9]
【问题讨论】:
-
“从 1 到 10 的 10 个唯一随机数,不重复” - 你能给个样本吗?
-
0 到 10(包括 0 不包括 10)只有一个数字序列没有任何重复数字:0 1 2 3 4 5 6 7 8 9。对于其他值可能有多个序列,恐怕您必须检查任何重复的值并替换它们,重复替换直到所有值都是唯一的。
-
如果数字必须是正整数,正如您所假设的那样,这意味着您的数字必然是 0、1、2、3、4、5、6、7、8、9。剩下的唯一随机性就是选择它们的顺序。
-
循环 i = 0 - N。从 0-N 中选择一个随机整数 r。交换替换[i] 和替换[r]。完成。
标签: java