假设我想生成1到100之间的随机数,但我不想包括42.如果不重复随机方法直到它不是42,我该如何做到这一点.
var nums = [Int](1...100)
nums.removeAtIndex(42)
let random = Int(arc4random_uniform(UInt32(nums.count)))
print(nums[random])
Run Code Online (Sandbox Code Playgroud)
Range当您想要排除多于1个值时,此扩展确实提供了解决方案.
extension Range where Element: Hashable {
func random(without excluded:[Element]) -> Element {
let valid = Set(self).subtract(Set(excluded))
let random = Int(arc4random_uniform(UInt32(valid.count)))
return Array(valid)[random]
}
}
Run Code Online (Sandbox Code Playgroud)
例
(1...100).random(without: [40,50,60])
Run Code Online (Sandbox Code Playgroud)
我相信第二种解决方案的计算复杂性是O(n)n是该范围中包含的元素数量.
这里的假设是调用者提供的n个排除值不超过n个.
| 归档时间: |
|
| 查看次数: |
986 次 |
| 最近记录: |