# arrays - random.choice python

## 从数组中选择元素,其概率与其值成比例 (3)

``````arr[0] = 100
arr[1] = 200``````

``````new randomNumber
for(int y=0; y < probabilities.length; y++){
if(randomNumber < probabilities[y]){
Select probabilities[y]
}
}``````

## 对于反比例：

1. 总结数组
2. 选择0到（n-1）* sum -1之间的随机数
3. 从开始开始累计和值，直到您> =为随机值。

## 这是为了成比例

1. 总结数组
2. 从0到sum-1之间选择一个随机数
3. 累积从数组开始的值，直到您的值大于随机值。

`` [10 60 5 25]  --> [10 70 75 100]``

``````Random variable x      Index in the Cumulative Array      Value in Original Array
-----------------      -----------------------------      ----------------------
0 <= x < 10                      0                            10
10 <= x < 70                      1                            60
70 <= x < 75                      2                             5
75 <= x < 100                     3                            25 ``````

``[10 60 5 25]  -->  [1/10  1/60  1/5  1/25]  -->  [1/10  7/60  19/60  107/300]``

``arr[] = [1,1,1,1,...(10 times),2,2,2,..(5 times),3,3,3,3,...(20 times)];``

``````int r = Random(0,arr.count);
int value = arr[r];``````