Search code examples
swiftprobability

Coding Probability in Swift


I want to write a program that creates say 100 squares, with the following rules:

  • up to - but no more than 10% of them will be blue
  • up to - but no more than 15% of them will be red
  • up to - but no more than 25% of them will be yellow
  • and the rest of them will be orange

So basically every time I run the App I'll get totally different results. For example, the first time I might get:

  • 9 blues
  • 13 reds
  • 18 yellows
  • and 60 oranges

The next time I might get:

  • 6 blues
  • 14 reds
  • 23 yellows
  • and 57 oranges

And so on.

I tried doing this using random numbers but every single time I get the absolute max # from each color category - I basically never had any classes in Probability (or Statistics) so I really have no idea what I'm doing here - thought maybe someone could point me in the right direction or knows how to do Probability in Swift code...?


Solution

  • This function will return an array of 100 randomized UIColors matching your probability requirement. This code includes a probability of zero for each of the three main colors. If you want to include a probability of at least one of each color then change the range to 1...n

    func generateRandomColors() -> [UIColor] {
    
        var randomColors = [UIColor]()
    
        randomColors += Array(repeating: .blue, count: .random(in: 0...10))
        randomColors += Array(repeating: .red, count: .random(in: 0...15))
        randomColors += Array(repeating: .yellow, count: .random(in: 0...25))
        randomColors += Array(repeating: .orange, count: 100 - randomColors.count)
    
        return randomColors.shuffled()
    }