gpt4 book ai didi

java - 具有 10 个不同随机元素且无重复的数组

转载 作者:行者123 更新时间:2023-11-30 03:45:04 25 4
gpt4 key购买 nike

我试图用 Random() 创建一个包含 10 个不同元素的数组,所以基本上我有这个

public static int[] RandomArray (int xArra[]) throws java.io.IOException {
Random Rand = new Random();
int nal;

for (int i = 0; i < xArra.length; i++) {
nal = Rand.nextInt(11); /*I would like to make this thing work with any
numbers, for example, changing this to 50 or 100.
In an array of 10 elements it should be
impossible to have a duplicate because with
11 it just prints from 1 to 10.
Thats why i put 11 here. */
for ( int j = 0; j < xArra.length; j++) {
if (nal == xArra[j]) {
nal = Rand.nextInt(11);
j=0;
}
}

xArra[i] = nal;

}

return xArra;

}

基本上我在 nal 中存储一个随机数,然后我在一秒钟内运行我的数组来检查这个随机数与已经给定的数字,如果它等于数组中给定的任何数字,它会再次随机更改它,并再次运行 For 检查新数字是否重复,如果不是,我存储在 xArra[i ].

当我运行 3 次时,结果如下所示:

首次运行:81643210897

第二次运行:93810714596

第三次运行:35236714109

所以,正如你所看到的,我几乎以为我拥有它,但它只重复 1 个数字,而不是 2 或 3 个,所以基本上我只是想让这个东西发挥作用。我只想打印 10 个随机数,不重复,不重复。

这是我的完整代码:

import java.io.*;
import java.util.*;

public class ArraynoR {

public static void main (String[] args) throws java.io.IOException {
int Array[]= new int [10];
RandomArray(Array);
for(int i=0; i<Array.length; i++){
System.out.println("Array[" + (i + 1) + "]:" + Array[i]);
}
}

public static int[] RandomArray (int xArra[]) throws java.io.IOException... //up

}

请原谅我糟糕的英语,我希望我能解释清楚。

谢谢!

最佳答案

不要存储和搜索重复项,而是创建一个包含感兴趣范围内的数字的ArrayList。使用Collections.shuffle() 随机化这些值,然后从随机集合中选择您想要的数量。保证不提供重复项,并且比搜索/拒绝方法更有效。

附录

也许不是最漂亮的代码,但它有效并给出了想法......

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class ShuffleDemo {

public static int[] RandomArray(int len) {
ArrayList<Integer> al = new ArrayList<Integer>(len);
for(int i = 1; i <= len; ++i) { // initialize the ArrayList with values 1 to len
al.add(i);
}
Collections.shuffle(al); // shuffle to random order
int[] results = new int[len];
// switching return type to ArrayList could eliminate the following loop
for(int i = 0; i < len; ++i) { // copy to array of ints
results[i] = al.get(i); // note: create a subset by reducing
} // the upper bound for this loop
return results;
}

public static void main(String[] args) {
System.out.println(Arrays.toString(RandomArray(10)));
}
}

关于java - 具有 10 个不同随机元素且无重复的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25954149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com