簡體   English   中英

如何生成某個范圍內的隨機數列表,然后獲取未包含在該列表中的數字

[英]How to generate a list of random numbers between a certain range, then get numbers not included in that list

我生成了一個包含 1 到 300 之間的 20 個唯一隨機數的列表,並將其用於我需要使用它的目的。 但是,我還需要將未添加到列表中的數字添加到另一個列表中,以便在另一個函數中使用。

這是我用來生成 20 個數字的隨機列表的代碼:

JToggleButton[][] p = new JToggleButton[5][4];
ArrayList<Integer> list = new ArrayList<Integer>();

    Random rand = new Random();
    for (int i = 0; i < p.length; i++) {
        for (int j = 0; j < p[i].length; j++) {

            int randomNum = rand.nextInt((300 - 1) + 1) + 1;

            while (list.contains(randomNum)) {
                randomNum = rand.nextInt((300 - 1) + 1) + 1;
            }

            list.add(randomNum);

// rest of code that I need the random number list for

我需要將這 20 個項目列表中未包含的其他 280 個數字放入另一個列表中,但我不確定如何實際獲取這些“未使用”的數字

如果你真的像你說的那樣需要兩個列表,那么這里有一種方法:

final int numberOfInts = 300;
List<Integer> excluded = new ArrayList<>();
for (int i = 1; i <= numberOfInts ; i++) {
    excluded.add(i);
}

Random rand = new Random();
List<Integer> included = new ArrayList();
for (int i = 0; i < p.length; i++) {
    included.add(excluded.remove(rand.nextInt(excluded.size())));
}

我花了很長時間才明白你的問題在問什么。

    ArrayList<Integer> otherNumbers = new ArrayList<Integer>();
    for(int x = 0; x < list.size(); x++) {
        if(!list.contains(x+1)) {
            otherNumbers.add(x+1);
        }
    }

您可以通過跳過 20 個數字列表包含的值來填充新列表。

我認為最好的方法是生成一個單獨的列表並用 1 到 300 之間的每個數字填充它。之后,只需遍歷生成的隨機數列表並從 1 到 300 列表中刪除這些元素。 像這樣的東西..

ArrayList<Integer> list300 = new ArrayList<Integer>();
For (int i = 1; i <= 300; i++) {
    list300.add(i);
}

For (int i = 0; i < list.size(); i++) {
    if (list300.contains(list[i])) {
        list300.remove(Integer.vaueOf(list[i]));
    }
}

您可以創建一個包含所有 300 個數字的List ,然后當您向另一個列表添加一個隨機數時,只需從List刪除具有所有值的相同數字:

創建列表:

    ArrayList<Integer> excludedNumbers = new ArrayList<>(300);
    for (int i = 1; i <= 300; i++){
        excludedNumbers.add(i);
    }

在當前代碼中添加一行:

ArrayList<Integer> randomList = new ArrayList<>();
Random rand = new Random();

for (int i = 0; i < p.length; i++) {
    for (int i = 0; i < p[i].length; i++) {

            int randomNum = rand.nextInt((300 - 1) + 1) + 1;

            while (randomList.contains(randomNum)) {
                randomNum = rand.nextInt((300 - 1) + 1) + 1;
            }

            excludedNumbers.remove((Integer) randomNum); // the new line
            randomList.add(randomNum);
    }
} 

Integer確保List使用Object remove 函數而不是int remove 選項。

我希望我答對了你的問題,因為這對我來說有點難以理解。 我會這樣做:

ArrayList<Integer> notIncludedNumbers = new ArrayList<Integer>();
for (int i = 0; i <= 300; i++){
   if (!list.contains(i))
      notIncludedNumbers.add(i);
}

您迭代從 1 到 300 的所有數字,如果它們不包含在您的列表中,並且帶有 20 個隨機數,則將它們添加到notIncludedNumbers列表中。 我希望我能幫上忙。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM