jeudi 20 septembre 2018

iOS (swift): How to pick a random object with a given probability

I have an array of type MyObject, which itself has a single property (probability) of type Double.

let A = MyObject(probability: 0.33)
let B = MyObject(probability: 0.25)
let C = MyObject(probability: 0.42)
let objects = [A, B, C]

How can I draw at random one element from objects given the probabilities of the MyObject instances that it contains, please?

For example, I expect 25% of the time that the object B will be selected.

Thanks for any help.




Aucun commentaire:

Enregistrer un commentaire