Swift 中的编码概率

Coding Probability in Swift

我想编写一个程序来创建 100 个方块,规则如下:

所以基本上每次我 运行 应用程序我都会得到完全不同的结果。例如,第一次我可能会得到:

下次我可能会得到:

以此类推

我尝试使用随机数来做这个,但每次我都从每个颜色类别中获得绝对最大值 # - 我基本上从来没有 类 在概率(或统计)中,所以我真的不知道是什么我在这里做 - 想也许有人可以指出我正确的方向或知道如何在 Swift 代码中做概率......?

此函数将 return 一组 100 个随机 UIColors 匹配您的概率要求。此代码包括三种主要颜色中每一种的零概率。如果您想包括每种颜色中至少一种的概率,请将范围更改为 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()
}