gpt4 book ai didi

swift - 生成随机数并检查重复项

转载 作者:行者123 更新时间:2023-11-28 08:48:26 25 4
gpt4 key购买 nike

我想知道是否有一种简单的方法可以检查六个不同随机数中的重复项。我想检查 6 个随机数中的 4 个以上是否相同以创建 if 语句。

例如;

let firstRandomNumber = arc4random_uniform(3) + 1
let secondRandomNumber = arc4random_uniform(3) + 1
let thirdRandomNumber = arc4random_uniform(3) + 1
let fourthRandomNumber = arc4random_uniform(3) + 1
let fifthRandomNumber = arc4random_uniform(3) + 1
let sixthRandomNumber = arc4random_uniform(3) + 1

有了这些随机数,如果其中四个或更多相同(例如 3, 3, 3, 3, 2, 1),我想执行和操作。有人知道怎么做吗?

最佳答案

这个呢

let allValues = [firstRandomNumber,secondRandomNumber, thirdRandomNumber, fourthRandomNumber,fifthRandomNumber, sixthRandomNumber]

let maxOccurrencies:(value:UInt32, times:Int)? = allValues
.reduce([UInt32:Int]()) { (var dict, elm) -> [UInt32:Int] in
dict[elm] = (dict[elm] ?? 0) + 1
return dict
}
.maxElement { $0.1 < $1.1 }


if let (value, times) = maxOccurrencies where times >= 4 {
print("The value \(value) does appear \(times) times")
}

关于swift - 生成随机数并检查重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34674762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com