要解決Java數組隨機數不能重復的問題,可以使用以下方法:
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class RandomArray {
public static void main(String[] args) {
int[] array = generateRandomArray(10, 1, 100);
for (int num : array) {
System.out.println(num);
}
}
public static int[] generateRandomArray(int length, int min, int max) {
if (length > (max - min + 1)) {
throw new IllegalArgumentException("生成不了指定范圍內的不重復隨機數!");
}
Random random = new Random();
Set<Integer> set = new HashSet<>();
while (set.size() < length) {
int randomNum = random.nextInt(max - min + 1) + min;
set.add(randomNum);
}
int[] array = new int[length];
int index = 0;
for (int num : set) {
array[index++] = num;
}
return array;
}
}
import java.util.Random;
public class RandomArray {
public static void main(String[] args) {
int[] array = generateRandomArray(10, 1, 100);
for (int num : array) {
System.out.println(num);
}
}
public static int[] generateRandomArray(int length, int min, int max) {
if (length > (max - min + 1)) {
throw new IllegalArgumentException("生成不了指定范圍內的不重復隨機數!");
}
int[] array = new int[length];
Random random = new Random();
for (int i = 0; i < length; i++) {
int randomIndex = random.nextInt(max - min + 1 - i) + i;
array[i] = randomIndex;
int temp = array[i];
array[i] = array[randomIndex];
array[randomIndex] = temp;
}
for (int i = 0; i < length; i++) {
array[i] = array[i] + min;
}
return array;
}
}
這兩種方法都是通過生成隨機數并存入數組中,保證隨機數不重復。第一種方法使用了Set集合,第二種方法使用了Fisher-Yates算法。可以根據具體的需求選擇使用哪種方法。