我想从5个元素的数组中随机选择一个元素:我想控制这5个元素中每个元素的出现概率。
示例:我有一个像这样的数组:[A B C D E]
我已经知道我可以在这里对Weighted random selection from array数组中的随机选择进行加权。
如何加权像这样的数组中包含的元素?
答案 0 :(得分:2)
您将使用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" )'