Swift中的编码概率

问题描述 投票:0回答:1

我想编写一个使用以下规则创建100个正方形的程序:

-最多-但其中不超过10%为蓝色-最多-但其中不超过15%的颜色为红色-至-但最多不超过25%的颜色为黄色-其余的将是橙色

所以基本上,每次我运行该应用程序时,我都会得到完全不同的结果。例如,第一次我可能会得到:-9布鲁斯-13红-18黄色-和60个橘子

下次我可能会得到:-6布鲁斯-14红-23黄色-和57个橘子

依此类推。

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

swift xcode probability
1个回答
0
投票

此函数将返回与您的概率要求匹配的100个随机UIColors数组。假设您要每种颜色至少有一种。如果要包括零概率,则将范围更改为0...n

func generateRandomColors() -> [UIColor] {

    var randomColors = [UIColor]()

    randomColors += Array(repeating: .blue, count: Int.random(in: 1...10))
    randomColors += Array(repeating: .red, count: Int.random(in: 1...15))
    randomColors += Array(repeating: .yellow, count: Int.random(in: 1...25))
    randomColors += Array(repeating: .orange, count: 100 - randomColors.count)

    return randomColors.shuffled()
}
© www.soinside.com 2019 - 2024. All rights reserved.