,你可以一個TreeMap
與關鍵,目前總以前的概率相應的對象和值,然後生成0
和1
之間的隨機數,最後使用ceilingEntry(K key)
獲得對應於第一鍵對象大於或等於當前的隨機值。
喜歡的東西:
List<String> objects = Arrays.asList("one","two","three");
List<Double> chance = Arrays.asList(0.25, 0.25, 0.5);
// Build the tree map
TreeMap<Double, String> map = new TreeMap<>();
double total = 0.0d;
for (int i = 0; i < objects.size(); i++) {
map.put(total += chance.get(i), objects.get(i));
}
System.out.printf("The generated is map %s%n", map);
// The generator of random numbers
Random generator = new Random();
// Generate a random value between 0 and 1
double value = generator.nextDouble();
// Get the object that matches with the generated number
String object = map.ceilingEntry(value).getValue();
System.out.printf("The current value is %f corresponding to '%s'%n", value, object);
輸出:
The generated map is {0.25=one, 0.5=two, 1.0=three}
The current value is 0,048460 corresponding to 'one'
所以在這裏:
- 如果隨機值低於或等於
0.25
,我們會得到「one
」。
- 如果隨機值在
0.25
(不包括)和0.50
(包括)之間,我們將得到「two
」。
- 如果隨機值介於
0.50
(不含)和1.0
(含)之間,我們將得到「three
」。
由於這樣的事實:nextDouble()
返回double
值0.0
和1.0
之間均勻分佈,這是不夠好,得到預期的分佈。
你的問題根本不清楚,你能分享一些代碼還是和輸入輸出結果? –
'相同的機會'是指如果孩子已經選擇了不再選擇所選的某個時間間隔? –
我認爲你的概率總和爲1?然後,只需使用'Math.random()'選擇一個數字[[0..1]'],然後遍歷可能的'List'和求和,直到找到第一個超過總和的元素。返回該索引處的項目。 –