0

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.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
ajrlewis
  • 2,968
  • 3
  • 33
  • 67
  • 2
    What does your current attempt look like and what is the issue with it? – Scriptable Sep 20 '18 at 12:30
  • Create an array of integers containing 0 to 99, and pick one randomly. – El Tomato Sep 20 '18 at 12:34
  • @Scriptable Messy -- inverting the CDF and mapping indices. Was hoping there would be an efficient method in Swift for this, please. – ajrlewis Sep 20 '18 at 12:34
  • In theory, if you draw between 0 and 100 (with a rand()%100), then divide by 100, and check whereas you are between `[0, 0.33]; [0.33, 0.33+0.25]; [0.33+0.25; 1]` should give you the desired result. – Larme Sep 20 '18 at 12:35
  • @ElTomato I could generate an array of 1000 elements, containing `(0.33 * 1000.0)` occurrences of `A`, etc. then pick one at random, but this is not the best way to do this type of problem. – ajrlewis Sep 20 '18 at 12:36
  • @Larme I guess that could work – ajrlewis Sep 20 '18 at 12:38
  • See the linked duplicate question and the accepted answer. In your case, `let selectedItem = objects[randomNumber(probabilities: [0.33, 0.25, 0.42])]`. You could even use `map` to extract the probabilities to pass to the function. – vacawama Sep 20 '18 at 12:47

0 Answers0