2017-01-31 101 views
0

我有以下問題:隨機選擇的對象用不同的概率

我需要選擇從List隨機對象。這很簡單,如果所有元素都有相同的選擇機會。

就我而言,拾取對象的機會存儲在另一個List中。所以我需要一種方法,它根據另一個List從列表中隨機選取一個元素。

編輯: 例如,

List<String> objects = Arrays.asList("one","two","three"); 
List<Double> chance = Arrays.asList(0.25, 0.25, 0.5); 

現在我想Stringone」和「two」以和一個有機會出去的四個Stringthree」一個的機會了兩個。

謝謝你的任何建議。

+0

你的問題根本不清楚,你能分享一些代碼還是和輸入輸出結果? –

+0

'相同的機會'是指如果孩子已經選擇了不再選擇所選的某個時間間隔? –

+0

我認爲你的概率總和爲1?然後,只需使用'Math.random()'選擇一個數字[[0..1]'],然後遍歷可能的'List'和求和,直到找到第一個超過總和的元素。返回該索引處的項目。 –

回答

2

,你可以一個TreeMap與關鍵,目前總以前的概率相應的對象和值,然後生成01之間的隨機數,最後使用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' 

所以在這裏:

  1. 如果隨機值低於或等於0.25,我們會得到「one 」。
  2. 如果隨機值在0.25(不包括)和0.50(包括)之間,我們將得到「two」。
  3. 如果隨機值介於0.50(不含)和1.0(含)之間,我們將得到「three」。

由於這樣的事實:nextDouble()返回double0.01.0之間均勻分佈,這是不夠好,得到預期的分佈。

+1

謝謝你,你的solutuion對我來說非常完美 – Jermano

+0

你如何獲得列表的工作?我剛剛得到一個錯誤 – TheCrazyProfessor

+0

什麼樣的錯誤? –