How do I specify chance when setting a variable to random item in array?
One way: set up a parallel array with the corresponding percentage chances; below, I've scaled them to 1000. Then, choose a random number between 1 and 1000 and iterate through the array until you've run out of chances:
#!/bin/bash
array=( "foo" "bar" "baz")
chances=(733 266 1)
choice=$((1 + (RANDOM % 1000)))
value=
for((index=0; index < ${#array[@]}; index++))
do
choice=$((choice - ${chances[index]}))
if [[ choice -le 0 ]]
then
value=${array[index]}
break
fi
done
[[ index -eq ${#array[@]} ]] && value=${array[index]}
printf '%s\n' "$value"
The shell can't do floating point math, but if we just move the decimal point, we can use $RANDOM
and integer math:
#!/usr/local/bin/bash
array=("foo" "bar" "baz")
dieroll=$(($RANDOM % 1000))
if [[ "$dieroll" -lt 1 ]]; then
printf "%s\n" "${array[2]}"
elif [[ "$dieroll" -lt 266 ]]; then
printf "%s\n" "${array[1]}"
else
printf "%s\n" "${array[0]}"
fi
This has the advantages of not having to blow the array up to 1000 entries or needing any for
loops.