[英]how to generate unique random numbers with a specific range
我想在此范圍內(0-255)產生255個唯一的隨機數。 這樣數組就不會包含重復的記錄
short [] array =new short[255];
Random rand = new Random();
boolean flag=false;
for (int i=0;i<array.length;i++){
int random_integer = rand.nextInt(255-0) + 0;
for (int j=0;j<i;j++){
if ((short)random_integer==array[j]){
flag=true;
}
}
if (flag==false){
array[i]=(short)random_integer;
}
}
for (int i=0;i<array.length;i++){
System.out.println(array[i]);
}
但是我只得到前20個0r 30個具有值的項,其余的數組項等於零。
解決方案1:
我閱讀了Jon Skeet的評論,當然,這是最簡單的解決方案:
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 255; i++) {
list.add(i);
}
//and here is the point. Java already have this implemented for you
Collections.shuffle(list);
或采用Java 8聲明式:
List<Integer> list= IntStream.range(0, 255)
.boxed()
.collect(Collectors.toList());
Collections.shuffle(list);
要么
List<Integer> list = new ArrayList<>();
IntStream.range(0, 255).forEach(list::add);
Collections.shuffle(list);
解決方案2(了解您的解決方案):
您需要為每個單元格生成一個數字,並檢查該數字是否已經存在:
short [] array =new short[255];
Random rand = new Random();
for (int i=0; i<array.length; i++) {
int random_integer = -1;
//generate integer while it exists in the array
while(exists(random_integer, array)) {
random_integer = rand.nextInt(255);
}
array[i] = random_integer;
}
現在,讓我們檢查它是否存在:
public boolean exists(int number, int[] array) {
if (number == -1)
return true;
for (int i=0; i<array.length; i++) {
if (number == array[i])
return true;
}
return false;
}
當然,例如,您可以使用哈希圖來加速exist exists()
方法,即將復雜度從O(n)降低到O(1);
如果可以使用Java 8:
List<Integer> randIntegers = new Random().ints(1, 256).distinct().limit(255).boxed().collect(Collectors.toList());
您檢查是否存在隨機數,但不要在循環中將標志重置為false,因此,一旦第一個重復數字出現,就不再發生任何事情,因為標志始終為true。
您還應該內置以下內容:
if ((short)random_integer==array[j]){
flag=true;
i--;
}
以確保在跳過重復編號后重新訪問數組的索引。
public static void main(String ar[]){
short [] array =new short[255];
Random rand = new Random();
int random_integer;
boolean flag=false;
for (int i=0;i<array.length;i++){
random_integer = rand.nextInt();
for (int j=0;j<i;j++){
if ((short)random_integer==array[j]){
flag=true;
i--;
}
}
if (flag==false)
array[i]=(short)random_integer;
}
for (int i=0;i<array.length;i++)
System.out.print(" "+array[i]);
System.out.println();
}
您需要在每次迭代中重置flag
值或更改邏輯:
for (int j=0;j<i;j++){
flag=false;//<--
if ((short)random_integer==array[j]){
flag=true;
}
}
您是否考慮過創建HashSet並放入您使用過的值? 然后您的代碼應如下所示:
HashSet hs = new HashSet();
short [] array =new short[255];
Random rand = new Random();
for (int i=0;i<array.length;i++){
int random_integer = rand.nextInt(255-0);
if (!hs.contains(random_integer ))
{
array[i]=(short)random_integer;
hs.put(random_integer);
}
else{ //generate new integer}
}
沒有適當的縮進,很難閱讀代碼。
無論如何-如果flag == true
您什么也不做。 因此,顯然您不會在數組中填充很多位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.