我想伪随机地从5个元素的数组中选择一个元素:我想控制这5个元素中每个元素的出现概率。
示例:我有一个这样的数组:[A B C D E]
我已经看到我可以在这里对数组中的随机选择进行加权:Weighted random selection from array。
如何对像这样的数组中包含的元素进行加权?
你可以使用bash内置变量RANDOM,稍加算术
weighted_selection() {
local ary=("$@")
case $(( RANDOM % 10 )) in
0) index=0 ;; # one out of ten
1) index=1 ;; # one out of ten
2|3) index=2 ;; # two out of ten
4|5) index=3 ;; # two out of ten
*) index=4 ;; # remaining is four out of ten
esac
echo ${ary[index]}
}
我们来测试一下:
a=(A B C D E)
declare -A count
for ((i=1; i<1000; i++)); do
(( count[$(weighted_selection "${a[@]}")]++ ))
done
declare -p count
输出
declare -A count='([A]="99" [B]="100" [C]="211" [D]="208" [E]="381" )'