簡體   English   中英

從ArrayList抓取隨機對象不是隨機的

[英]Grabbing random object from ArrayList is not random

我正在創建一個方法,如果您傳入類型為Random的參數,則它將返回一個隨機對象。 這基本上是我想要做的:

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] 2,2,2,1,1,1,1,1 [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
    }

但是我的輸出不是隨機的。 我使用了調試器,發現我的select方法生成的整數相對較低,因此它將始終打印出2或1,而不會打印c或a。 我不知道為什么會這樣,將不勝感激。

編輯:問題已解決。 我省略了很多細節,但是當我調用size()方法時,我改寫了一些東西,該東西有一個錯誤,該錯誤返回的數字比我想要的小。 感謝dtech注意到我的愚蠢錯誤。 謝謝所有試圖幫助我的人!

乍看之下,代碼似乎沒有問題,因此可能只是隨機結果。 但是您的“打印並檢查”方法非常不可靠。 只需使用以下內容:

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 a:2857

僅當數字確實不同時,您才應關注。

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

發送給您隨機初始化代碼,您每次得到的結果完全一樣嗎? 您是否正在使用種子創建隨機對象?

這是我使用的代碼。 您需要提供更多代碼,以查看您的代碼為什么不起作用。

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

暫無
暫無

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

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