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.
4
Answers
Add
1
10 times to your array,2
20 times, and so on. YourArray
will have 100 elements so you will control the probability for each element.If your values are always going to be multiples of 5% you can use an array of 20 elements and add a proportional number of values.
more of a mathematical question than an UI question, but nevertheless:
and to prove it:
firstIndex
.)more efficient: