我有一个循环,它将随机生成的整数分配给一个数组。 我需要一种方法来确保相同的整数不会两次输入到数组中。
我认为在整个循环中创建一个循环会起作用,但我不确定在这里执行什么。
int wwe[] = new int[9];
for(int i = 0; i < 9 ; i++){
int randomIndex = generator.nextInt(wwe.length);
wwe[i] = randomIndex;
System.out.println(wwe[i]);
System.out.println("########");
for(int j = 0; j < 9; j++){
System.out.println("This is the inner element " + wwe[j]);
}
}
答案 0 :(得分:4)
答案 1 :(得分:1)
你实际上正在寻找改组你的阵列。
请注意,您真正想要的是找到数组的随机顺序,这称为permutation。
在java中,可以使用带有 Collections.shuffle()
的列表来完成。
如果您希望自己实现它 - 使用fisher yates shuffle,它很容易实现。
由于其他答案显示了如何使用Collections.shuffle() - 这是一个简单的实现+ fisher yates shuffle的示例,它不需要将原始数组转换为列表。
private static void swap (int[] arr, int i1, int i2) {
int temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
private static void shuffle(int[] arr, Random r) {
for (int i =0; i < arr.length; i++) {
int x = r.nextInt(arr.length - i) + i;
swap(arr,i,x);
}
}
public static void main(String... args) throws Exception {
int[] arr = new int[] {1 , 5, 6, 3, 0, 11,2,9 };
shuffle(arr, new Random());
System.out.println(Arrays.toString(arr));
}
答案 2 :(得分:1)
类似以下内容应符合您的要求 它使用HashSet来实现独特的元素。
Set<Integer> sint = new HashSet<>();
Random random = new Random();
while ( sint.size() < 9){
sint.add(random.nextInt());
}
答案 3 :(得分:0)
例如,您可以使用Collections.shuffle
public static void main(String[] args) {
List<Integer> a = new ArrayList<>(9);
for (int i = 0; i < 9; i++) {
a.add(i);
}
Collections.shuffle(a);
System.out.println(a);
}