2011-03-06 86 views
0

我正在創建一個方法,如果您傳入Random類型的參數,那麼它將返回一個隨機對象。這基本上就是我想要做的事:從ArrayList中抓取隨機對象不是隨機的

public T choose(Random r) { 
    int randomInt = r.nextInt(randomList.size()); // randomList is just a instance variable 
    return randomList.get(randomInt); 
} 

隨機列表中有下面這樣的字符串:[2, 2, 2, 1, 1, 1, 1, c, c, c, a, a, a, a]

然後我做了下面的代碼驅動程序

for (int i = 0; i < 10; i++) { 
     System.out.print(rndList.choose(rnd)); // rnd is initialized as a static Random variable 
    } 

但是我的輸出不是隨機出現的。我使用調試器,發現我的選擇方法會生成一個相對較低的整數,所以它總是會輸出2或1,但不會輸出c或a。我無法弄清楚爲什麼會發生這種情況,不勝感激。

編輯:問題解決了。我遺漏了很多細節,但是當我調用size()方法時,這是我重寫的錯誤,它會返回比我想要的更小的數字。感謝dtech注意到我愚蠢的錯誤。感謝所有試圖幫助我的人!

+2

你試過運行它'50'次的例子嗎? – 2011-03-06 16:10:57

+2

另外,你是如何構建你的隨機數發生器?用Random()或Random(someConstantIntegerValue)'?如果使用後者,請注意每次運行程序時都會得到相同的「隨機」序列。 – 2011-03-06 16:14:00

+0

您可以創建一個完整的可運行測試程序嗎?看起來你的錯誤不在你在這裏發佈的代碼之外。 – 2011-03-06 16:17:07

回答

1

向您發送隨機初始化代碼,您是否每次獲得完全相同的結果?你使用種子來創建Random對象嗎?

4

乍一看沒有什麼看起來與代碼錯誤,所以它可能只是一個隨機結果。但是你的「打印和檢查」方法是非常不可靠的。只要使用這樣的事情:

final int N = 10000; // test 10.000 times 
HashTable<Object, Integer> count = new HashTable(N); 
for(int i=0;i < N;i++){ 
    Object o = rndList.choose(rnd); 
    count.put(o, (count.get(o)==null?0:count.get(o))+1); 
} 
for(Map.Entry<Object, Integer> map : count.entrySet()){ 
    System.out.println(String.format("%s: %d", map.getKey().toString(), map.getValue())); 
} 

這將打印上平均是這樣的: 2:1429 1:2857 C:2143 一:2857

只有當數字creatly不同,你應該關心。

還要確保您使用新的Random()構造函數,而不是新的Random(somenumber)。如果你使用後者,你每次都會得到相同的數字序列。

+0

我將您的方法放在我的驅動程序中,並且我一直得到2在7500左右,1在2500左右,並沒有提及a或c。我不知道發生了什麼。在我的驅動程序中,我創建了一個靜態變量Random,如下所示:static Random rnd = new Random();我不知道發生了什麼事! – Isai 2011-03-06 16:31:46

+1

不是你的randomList.size()的錯誤呢?這些數字似乎來自randomList.size(),返回4,這是List中元素的數量。你不是使用返回Set/List中唯一元素數量的方法嗎?你不是使用Set類而不是List類嗎? – dtech 2011-03-06 16:36:58

+0

哇你解決了我的問題哈哈。我知道我在代碼中遺漏了很多東西,但我正在編寫一個地圖的抽象,並且我使用了實際上比ArrayList小的地圖的大小。 – Isai 2011-03-06 16:43:15

1

這是我使用的代碼。你需要提供更多的代碼來了解爲什麼你不工作。

public class Main<T> { 
    private List<T> randomList = new ArrayList<T>(); 

    public T choose(Random r) { 
     int randomInt = r.nextInt(randomList.size()); // randomList is just a instance variable 
     return randomList.get(randomInt); 
    } 


    public static void main(String... args) throws IOException, InterruptedException, ExecutionException { 
     Main<String> rndList = new Main<String>(); 
     rndList.randomList.addAll(Arrays.asList("2, 2, 2, 1, 1, 1, 1, c, c, c, a, a, a, a".split(", "))); 

     Random rnd = new Random(); 
     for (int i = 0; i < 10; i++) { 
       System.out.print(rndList.choose(rnd)); // rnd is initialized as a static Random variable 
      } 

    } 
} 

打印

1ca1caa1a2