How to increase or decrease the probability of an item being picked from an array?

Lets say I have an array of numbers like this:

// Create Array Of Numbers
let numbers = ["1","2","3","4","5"]

If I want to print a random number from the array, I can do something like:

pickedNumber = Int.random(in: 0...numbers.count - 1)

The above line will return a random value from my array. What I would like to do is, set a probability for each value in the array. For example:

- 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% 

What's the best approach for this? Any guidance or advice would be appreciated. This problem I am facing is in swiftUI.

hi,

the easiest, fastest way might just be to change the definition of numbers, so that the elements appears with the frequencies you like. since we're talking 1/20-ths here (multiples of 5%), give the array 20 elements:

let numbers = ["1", "1", "2", "2", "2", "2", "3", "3", "3", "3", "3", "3", "4", "4", "4", "4", "4", "4", "4", "5"]

if let pickedNumber = numbers.randomElement() {
	print(pickedNumber)
}

there are more general ways to do this, but keep it simple for now ..

hope that helps,

DMG

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"!

Was that helpful, @TanavSharma?

How to increase or decrease the probability of an item being picked from an array?
 
 
Q