あなたでし対応するオブジェクト前の確率の値として、現在の合計が、その後で最初のキーに対応するオブジェクトを取得するにはceilingEntry(K key)
を使用し、最終的0
と1
の間の乱数を生成し、そしてなどキーでTreeMap
現在のランダム値より大きいか等しい。
のような何か:
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()
が均一0.0
と1.0
間を分散double
値を返すという事実のおかげで、これは予想される分布を取得するのに十分良いです。
あなたの質問は全く明確ではありません。いくつかのコードを入力して出力結果を入力できますか? –
「同じチャンス」とは、子供が既に選択したインターバルのピックを選択していない場合です。 –
私はあなたの確率合計を1と仮定しますか?それから、 'Math.random()'を使って数字 '[0 .. 1]'を選び、あなたの合計を超える最初の要素が見つかるまでおそらく 'List'とsumを歩きます。そのインデックスでアイテムを返します。 –