Chance of 1 being picked at 10%
Chance of 2 being picked at 20%
Chance of 3 being picked at 30%
Chance of 4 being picked at 35%
Chance of 5 being picked at 5%
I would try something like this:
Get a random number between 1 and 100 (since you are using percentages, that makes it easy)
Allocate ranges between 1 and 100, depending on your probabilities...
func randomIndex() -> Int {
switch Int.random(in: 1...100) {
case 1...10:
return 0
case 11...30:
return 1
case 31...60:
return 2
case 61...95:
return 3
default:
return 4
}
}
This returns a random index to your array, based on the probabilities you have given. It hard-codes the 5 values and probabilities, but you could write a more advanced/flexible version, if that would suit your use-case better.
Rather than returning an index, you could do the look-up in the function, like this:
func chooseFromArray() -> String {
switch Int.random(in: 1...100) {
case 1...10:
return numbers[0]
case 11...30:
return numbers[1]
case 31...60:
return numbers[2]
case 61...95:
return numbers[3]
default:
return numbers[4]
}
}
Note that your array contains "Strings", not "Numbers"!