如何生成9个介于1到9之间的随机数,且不重复,一个接一个地生成。就像这样:
假设第一个随机数生成的是4,那么下一个随机数必须在[1, 9] - {4}内。
我的第一种方法是将每个随机生成的数字添加到一个集合中,以避免重复。但是,在更糟糕的情况下,例如我们已经生成了6个数字并且还需要生成3个数字时,该过程会变得有点慢。而当范围从[1, 9]更改为[1, 1000]时,这种方法听起来就不正确了。
有人能提出另一种方法吗?
从排序的数组开始(通过循环轻松创建);然后通过交换每个数组元素与另一个(随机选择的)元素来进行洗牌。为避免评论中讨论的偏差,其他元素的索引必须等于或高于第一个元素的索引。 如果索引相等,则元素不会被交换。(此答案的原始版本包含一句关于元素可能被交换回来的话,但现在已经过时,因为这不能再发生了。)
List
),其中包含Integer
(从start
到end
,例如在您的例子中,start=1
且end=9
),然后使用Collections.shuffle(list);
方法进行随机排列,例如:static List<Integer> randArray(int start, int end) { //specify start/end
List<Integer> randList=new ArrayList<>(end-start+1); //create list
for (int k=start;k<=end;k++) { //generate integers in order
randList.add(k); //add integers to the list
}
Collections.shuffle(randList); //reoder randomly the list
return randList; //return the list with items in random order
}
< p > shuffle
方法只是随机重新排列列表中的项目。
int arr[]=new int[9];
for(int i=0;i<9;i++)
arr[i]=i+1;
现在对给定的数组进行shuffle
操作。
如何对数组进行洗牌?
To shuffle an array a of n elements (indices 0..n-1):
for i from n - 1 downto 1 do
j = random integer with 0 <= j <= i
exchange a[j] and a[i]
参考资料
使用Java 8,Enne的方法可以写成这样:
private static List<Integer> generateRandom( int low, int high )
{
List<Integer> range = IntStream.range( low, high ).boxed()
.collect( Collectors.toList() );
Collections.shuffle( range );
return range;
}
public ArrayList<Integer> getRandom(int numbers,int min_value, int max_value)
{
HashSet<Integer> list = new HashSet<>();
Random r = new Random();
while (list.size()<numbers) {
list.add(r.nextInt(max_value - min_value) + min_value);
}
return new ArrayList<>(list);
}
替代方案:
public ArrayList<Integer> getRandom(int numbers,int min_value, int max_value)
{
Random r = new Random();
ArrayList<Integer> list = new ArrayList<>();
for(int i=min_value; i<=max_value;i++)
list.add(i);
while (list.size()>numbers) {
list.remove(r.nextInt(list.size()));
}
Collections.shuffle(list);
return list;
}
替代方案:
public ArrayList<Integer> getRandom(int numbers, int min_value, int max_value) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = min_value; i <= max_value; i++) {
list.add(i);
}
Collections.shuffle(list);
return new ArrayList<>(list.subList(0, numbers));
}
索引0->索引1->索引2...
[1] -> [2] -> [3]....
生成一个介于0和list.size()之间的随机索引值,并获取列表中的位置:yourNumberResult = get(randomIndexValue).
然后从列表中删除该位置:list.remove(randomIndexValue)
然后重复这个过程,直到list.size()==0