Reputation: 37
I want to pseudo-randomly pick one element from an array of 5 elements: I want to control the occurrence probability of each of those 5 elements.
Example: I have an array like this: [A B C D E]
I have seen that I can weight a random selection from an array here: Weighted random selection from array.
How can I weight elements contained in an array like this?
Upvotes: 1
Views: 544
Reputation: 247210
You'd use the bash builtin variable RANDOM, with a little arithmetic
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]}
}
Let's test it:
a=(A B C D E)
declare -A count
for ((i=1; i<1000; i++)); do
(( count[$(weighted_selection "${a[@]}")]++ ))
done
declare -p count
outputs
declare -A count='([A]="99" [B]="100" [C]="211" [D]="208" [E]="381" )'
Upvotes: 2