修改复制随机数生成器为非复制随机数生成器
Modify duplicating random number generator to non-duplicating random number generator
int size = 5;
int[] list = new int[size];
Random rand = new Random();
for(int i = 0; i < size; i++)
{
list[i] = rand.nextInt(100);
}
for(int element : list)
System.out.print(element + " ");
我正在尝试修改此随机数生成器,使其不会重复随机生成的数字。我怎样才能做到这一点?感谢您的帮助。
您可以将生成的值存储在 Set
中(这是一个包含 unique 元素的数据结构)。
每次生成新号码时,您可以检查它是否已经存在于Set
中。例如:
Set<Integer> set = new HashSet<Integer>();
Random rand = new Random();
for(int i = 0; i < size; )
{
int next = rand.nextInt(100);;
if (!set.contains(next)) {
set.add(next);
i++;
}
}
请注意,我只在生成尚未生成的数字时增加索引。
可以想象的最愚蠢的方法实际上是一个可以接受的策略:只丢弃数组中已经存在的任何生成的数字。无论您想对此进行改进,您都将面临 space 或时间成本(或两者兼而有之)。对于问题中显示的数组大小,没有必要。
有多种方法可以做到这一点。现有内容的简单变体:
int size = 5;
int[] values = new int[100];
int[] list = new int[size];
for( int i = 0; i < 100; i++ ) values[i] = i;
Random rand = new Random();
int ctListSize = 0;
int xList = 0;
while( true ){
int iCandidateValue = rand.nextInt(100);
if( values[ iCandidateValue ] == 0 ) continue; // already used
list[ xList++ ] = iCandidateValue;
values[ iCandidateValue ] = 0;
if( xList == size || xList == 100 ) break;
}
for(int element : list) System.out.print(element + " ");
有一个列表,其中包含您在 RNG 中看到的所有数字。然后检查列表是否存在 - 如果存在,请不要将其添加到列表中。如果它没有添加到列表中。
for (int i = 0; i < array.length; i++){
int num = rand.nextInt(100);
if (list.contains(num){
break;
}else{
list.add(num);
}
这样您就可以 return 列表并且看不到重复项。
或者考虑使用只允许唯一键的 Set 数据结构。
int size = 5;
int[] list = new int[size];
Random rand = new Random();
for(int i = 0; i < size; i++)
{
list[i] = rand.nextInt(100);
}
for(int element : list)
System.out.print(element + " ");
我正在尝试修改此随机数生成器,使其不会重复随机生成的数字。我怎样才能做到这一点?感谢您的帮助。
您可以将生成的值存储在 Set
中(这是一个包含 unique 元素的数据结构)。
每次生成新号码时,您可以检查它是否已经存在于Set
中。例如:
Set<Integer> set = new HashSet<Integer>();
Random rand = new Random();
for(int i = 0; i < size; )
{
int next = rand.nextInt(100);;
if (!set.contains(next)) {
set.add(next);
i++;
}
}
请注意,我只在生成尚未生成的数字时增加索引。
可以想象的最愚蠢的方法实际上是一个可以接受的策略:只丢弃数组中已经存在的任何生成的数字。无论您想对此进行改进,您都将面临 space 或时间成本(或两者兼而有之)。对于问题中显示的数组大小,没有必要。
有多种方法可以做到这一点。现有内容的简单变体:
int size = 5;
int[] values = new int[100];
int[] list = new int[size];
for( int i = 0; i < 100; i++ ) values[i] = i;
Random rand = new Random();
int ctListSize = 0;
int xList = 0;
while( true ){
int iCandidateValue = rand.nextInt(100);
if( values[ iCandidateValue ] == 0 ) continue; // already used
list[ xList++ ] = iCandidateValue;
values[ iCandidateValue ] = 0;
if( xList == size || xList == 100 ) break;
}
for(int element : list) System.out.print(element + " ");
有一个列表,其中包含您在 RNG 中看到的所有数字。然后检查列表是否存在 - 如果存在,请不要将其添加到列表中。如果它没有添加到列表中。
for (int i = 0; i < array.length; i++){
int num = rand.nextInt(100);
if (list.contains(num){
break;
}else{
list.add(num);
}
这样您就可以 return 列表并且看不到重复项。
或者考虑使用只允许唯一键的 Set 数据结构。