如何从数组中随机加权元素然后根据这些权重选择它?

问题描述 投票:0回答:1

我想伪随机地从5个元素的数组中选择一个元素:我想控制这5个元素中每个元素的出现概率。

示例:我有一个这样的数组:[A B C D E]

  • 我希望有机会选择A:0.10(10%)
  • 我想要选择B的概率:0.10(10%)
  • 我想要选择C的概率:0.20(20%)
  • 我想要选择D的概率:0.20(20%)
  • 我想要选择E的概率:0.40(40%)

我已经看到我可以在这里对数组中的随机选择进行加权:Weighted random selection from array

如何对像这样的数组中包含的元素进行加权?

arrays bash random weight
1个回答
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" )'
© www.soinside.com 2019 - 2024. All rights reserved.