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

时间:2019-03-05 23:22:50

标签: arrays bash random

我想从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数组中的随机选择进行加权。

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

1 个答案:

答案 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" )'