samedi 4 mai 2019

How to add weights when choosing a random element from an array

In swift you can use the .randomElement() to get a random element from that array. How can you extend this function to allow weights so that it favours the higher weighted elements. For example if you've got a casino roulette game you could have an array like this

let game = ["Black", "Red", "Green"] 

In this case there are 18 black and red but only one green therefor picking a random one should favour the black and the red more than the green.

In python you can use the .choices() and add a weights attribute. How can I do this in swift?

Thank you




Aucun commentaire:

Enregistrer un commentaire