簡體   English   中英

生成兩個隨機整數並將其從再次生成中刪除

[英]Generate two random integers and remove them from being generated again

我有一個Car對象的ArrayList,我想隨機選擇其中兩個並進行比較。 一旦我們比較了它們,我希望將劣質汽車“移走”,以免再次被隨機挑選。 我認為我們無法阻止特定數字的產生,因此我想到了其他一些想法。

這是我一直在想的一些事情:

Idea 1:
Include a "seen" attribute for each Car, set to false.
Generate two random integers from 0 to size of Car List.
Check to make sure two indexes are not seen.
Check to make sure that two integers are not the same, if they are, regenerate and repeat.
Grab cars using the two indexes generated. 
If not seen, compare and flag the inferior as seen. 
If seen, store that cars index in a seenIndex array.

Idea 2:
Create a copy (would a deep copy be required here, im thinking no?) of the list of Cars.
Generate two random numbers, confirm they're not the same. 
Compare cars, remove the inferior car from the copyList.
Repeat.

我傾向於想法2,但如果有一個更優雅的解決方案,我很想聽聽。

正如其他人所說的那樣,第一種想法雖然可行,但對於大小合適的汽車清單卻不可行。

我會選擇2

關於確認兩個隨機數不一樣的一件事-我建議您不要創建另一個隨機數,而是這樣做:

Random rnd = new Random()

int rand1 = rnd.nextInt(copyList.size() - 1); 
int rand2 = rnd.nextInt(copyList.size() - 2);

if(rand2 >= rand1) rand2++;

這樣可以避免創建一個可能與您必須替換的隨機數相同的隨機數,從而使您的程序快得多。

但是,如果您只是想弄出哪輛車更好,則可以遍歷一列Car類(或列表),將每個類與當前最好的類進行比較(其中cars是一組cars,getPoints()返回如何好車是):

int bestIndex = 0;

// Loop starts at 1 b/c we don't need to compare index 0 w/ 0
// i.e. # of comparisons is 1 minus the # of Cars
for(int i = 1; i < cars.length - 1; i++){ 

    if(cars[i].getPoints() > cars[bestIndex].getPoints()){
        bestIndex = i;
    }

}

這將保留陣列並有效地找到最佳汽車。 當然,可以為列表進行修改。

您的想法2是我建議的一種非常簡單的方法。

唯一要更改的是,副本arraylist不必是深層副本。 這是因為對於淺表副本(較便宜的副本),從一個列表中刪除一項不會影響另一列表。

您肯定不希望跟蹤使用了哪些indecs ,就像其他答案所暗示的那樣。
這篇數學文章解釋了為什么其他答案不是一個好主意。 數學運算不能直接轉換為該示例,因為有多個目標數字(最后一次迭代除外),但是在命中之前仍然有大量的預期嘗試次數,尤其是從更大的汽車列表開始時。

或者,您可以將隨機生成的數字存儲在數組列表中,然后每次生成新的隨機數時,可以先檢查數組,如果不包含該數字,則可以選擇它。 您可以這樣做:

public int generateRandomNumber(int start, int end, ArrayList<Integer> excludedNumbers) {
    Random rand = new Random();
    int range = end - start + 1;
    int random = rand.nextInt(range) + 1;
    while(excludedNumbers.contains(random)) { 
        random = rand.nextInt(range) + 1;
    }

    return random;
}

暫無
暫無

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

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