0

I want to "randomly" select from a collection in Swift but have certain instances be selected at different frequencies. Currently I am using.

let collection: [Int] = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
let random: Int = Int(arc4random_uniform(UInt32(collection.count)))
let selection: Int = collection[random]

I need the code to be compliant with Swift 2.0+.

Cody Weaver
  • 4,756
  • 11
  • 33
  • 51
  • How is this code not what you need? Is it not Swift 2 compliant? – Jongware Dec 11 '15 at 22:44
  • 1
    Something like this [Generate random numbers with a given distribution](http://stackoverflow.com/questions/30309556/generate-random-numbers-with-a-given-distribution) ? – Martin R Dec 11 '15 at 23:03
  • 1
    Similar code was reviewed here: [Weighted Probability Problem in Swift](http://codereview.stackexchange.com/questions/112605/weighted-probability-problem-in-swift). – Martin R Dec 11 '15 at 23:16

1 Answers1

2

If you're able to target iOS 9.0 or later, GameplayKit has a great solution called GKGaussianDistribution, which lets you generate random numbers in a range where the frequency of each number matches a bell curve like this:

Frequency of Dice Rolls on a D20 with Gaussian Distribution

To use this, just import GameplayKit into your project, then use this code:

let distribution = GKGaussianDistribution.d6()
print(distribution.nextInt())

That uses a six-sided die, but you can use any range you want. You might find my tutorial on GameplayKit random number generation useful.

TwoStraws
  • 12,862
  • 3
  • 57
  • 71