Java - 生成特定数字的随机范围而不重复这些数字 - 如何?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5224877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - generate Random range of specific numbers without duplication of those numbers - how to?
提问by katura
Sounds simple enough...but I've been plugging away at this, trying to find the one and all solution.
听起来很简单……但我一直在努力解决这个问题,试图找到唯一的解决方案。
For a range of numbers, say 1-12, I want to generate a random sequence within that range, andinclude 1and 12.
对于一系列数字,比如1-12,我想在该范围内生成一个随机序列,并包括1和12。
I don't want duplicate numbers though.
我不想要重复的数字。
So I would want something like this - 3,1,8,6,5,4 ..and so on, every number from 1-12.
所以我想要这样的东西 - 3,1,8,6,5,4 ..等等,从 1 到 12 的每个数字。
Then I want to put these random numbers into an Array
and use that array to 'randomly' select and display some items (like inventory pulled from database) on a jsp page.
然后我想将这些随机数放入一个Array
并使用该数组在 jsp 页面上“随机”选择和显示一些项目(如从数据库中提取的库存)。
The problem with what I've tried thus far, is that there are a lot of duplicatenumbers being generated...or, not ALLof the numbers are chosen.
到目前为止,我尝试过的问题是生成了很多重复的数字……或者,不是所有的数字都被选中。
Is there a simple solution to this problem?
这个问题有简单的解决方案吗?
Edit
编辑
Test#1 using Collections
and shuffle()
method -
测试#1 使用Collections
和shuffle()
方法 -
ArrayList<Integer> list = new ArrayList<Integer>(10);
for(int i = 0; i < 10; i++)
{
list.add(i);
}
Collections.shuffle(list);
String[] randomNumbers = (String[])list.toArray();
for(int i = 0; i < 10; i++)
{
out.print(randomNumbers[i]+"<br>");
}
The result was a sequence with duplicate values -
chose = 3
chose = 8
chose = 7
chose = 5
chose = 1
chose = 4
chose = 6
chose = 4
chose = 7
chose = 12
结果是一个具有重复值的序列 -
选择 = 3
选择 = 8
选择 = 7
选择 = 5
选择 = 1
选择 = 4
选择 = 6
选择 = 4
选择 = 7
选择 = 12
Test #2 - using Random math class
测试 #2 - 使用随机数学课
int max = 12;
int min = 1;
int randomNumber = 0;
String str_randomNumber = "";
for(int i=0; i<10; i++) {
//int choice = 1 + Math.abs(rand.nextInt(11));
int choice = min + (int)(Math.random() * ((max - min) + 1));
out.print("chose = "+choice+"<br>");
}
The result was just like using Collections.shuffle()
.
结果就像使用Collections.shuffle()
.
回答by Howard
You can fill an array with all values from 1 to 12 and then shuffle them (see e.g. Why does Collections.shuffle() fail for my array?)
您可以使用从 1 到 12 的所有值填充数组,然后将它们混洗(参见例如为什么 Collections.shuffle() 对我的数组失败?)
回答by Andrey Adamovich
You can put all numbers from 1 to 12 in order into array and then use some shuffling algorithm to randomize the order of them e.g. http://www.leepoint.net/notes-java/algorithms/random/random-shuffling.html.
您可以将 1 到 12 的所有数字按顺序放入数组,然后使用一些改组算法来随机化它们的顺序,例如http://www.leepoint.net/notes-java/algorithms/random/random-shuffling.html。
回答by Mehdi
This is a utility method for creating a random Integer number :
这是用于创建随机整数的实用方法:
public static int randomInteger(int min, int max) {
Random rd = new Random();
return rd.nextInt((max - min) + 1) + min;
}
This is an algorithm that always produces a unique Set of integers:
这是一种始终生成唯一整数集的算法:
public static Set<Integer> makeRandomSet(int howManyNumber, int startNumber, int endNumber){
Set<Integer> integerSet = new HashSet<>();
boolean couldBeAdded = false;
for(int i=0; i< howManyNumber; i++) {
while (!couldBeAdded) {
Integer randomInt = randomInteger(startNumber, endNumber);
couldBeAdded = integerSet.add(randomInt);
}
couldBeAdded = false;
}
return integerSet;
}
We made use of add methodreturn type to check the duplicate value within our Set.
我们使用add 方法返回类型来检查 Set 中的重复值。
And here is the test code:
这是测试代码:
public static void main(String[] args) {
Set<Integer> randomSet = makeRandomSet(6, 1, 54);
System.out.println(randomSet);
}
The output of the above code is 6 random unique integers number between 1 and 54
上述代码的输出是1 到 54 之间的 6 个随机唯一整数
回答by DwB
Random number generation allows for duplications. If you want a range of random numbers without duplication, I suggest the following:
随机数生成允许重复。如果你想要一系列没有重复的随机数,我建议如下:
- Generate a random number (I will refer to this a numberX).
- Add to a Set object.
- Check the size of the Set object, if it is the desired size, you are done. If it is smaller than the desired size, goto step 1
- 生成一个随机数(我将其称为 numberX)。
- 添加到 Set 对象。
- 检查Set对象的大小,如果是想要的大小,就大功告成了。如果它小于所需的大小,请转到步骤 1
回答by guru
If you are using MySQL or SQLLite as your database you can do this randomization at the SELECT query level by using ORDER BY RAND() for restricting to 1-12 you can put a where clause WHERE ID >=1 AND ID <=12 ORDER BY RAND()
如果您使用 MySQL 或 SQLLite 作为您的数据库,您可以使用 ORDER BY RAND() 在 SELECT 查询级别执行此随机化以限制为 1-12 您可以放置一个 where 子句 WHERE ID >=1 AND ID <=12 ORDER兰德()
回答by brent777
You could just put all the numbers you want in a List and then order the List randomly and then convert the randomly ordered list to an array, e.g.
你可以把你想要的所有数字放在一个列表中,然后随机排序列表,然后将随机排序的列表转换为数组,例如
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 12; i++) {
list.add(i);
}
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Math.random() > 0.5 ? 1 : -1;
}
);
Integer[] array = list.toArray(new Integer[list.size()]);