0

Generally, I know that I can get a random element of an array in the following way:

var myArray = [x, y, z]
let myArrayLength = UInt32(myArray.count)
let myArrayIndex = Int(arc4random_uniform(myArrayLength))
let randomElement = myArray[myArrayIndex]

But how can I make the possibility of y being the random element twice the possibility of x and z being the random element thrice the possibility of y?

UPDATE

NB: Where x, y and z are CGPoints

Containment
  • 239
  • 2
  • 12
  • 4
    You're probably looking for something called "weighted random": http://stackoverflow.com/questions/30309556/generate-random-numbers-with-a-given-distribution – Tom C Aug 31 '16 at 15:16
  • @TomC I understand Martin R's solution to get the probabilities in the link you provided but not too sure how to apply those probabilities to say, an array of `CGPoint`s in my case. – Containment Sep 01 '16 at 18:44

1 Answers1

2

An easy way is to rewrite your array like this: [x,x,y,z]. Then, the probability of getting x becomes 0.5, the probability of y becomes 0.25 and the probability of z becomes 0.25. Just repeat the symbols with high probability as much as you want, for example [x, y, y, z, z, z, z] is good for what you asked for.

AhmadWabbi
  • 2,253
  • 1
  • 20
  • 35
  • Thanks, but how will I manage a scenario that with a large array. I guess this is simpler to implement for smaller arrays. – Containment Sep 01 '16 at 18:49
  • This solution works in simple cases. But even for large arrays, you can iterate on your original array `myArray`, and for each element, repeat it multiple times in another array using a nested loop. For a general method, you can refer to the comment of Tom C on your question. – AhmadWabbi Sep 01 '16 at 20:49