产生的数字必须与 arc4random 彼此不同
Produced Numbers are must different each other with arc4random
我想使用 arc4random 但生成的数字必须彼此不同。
我如何做这个例子?
您可以使用 Set
轻松实现:
var randomSet: Set<Int> = [] //Sets guarantee uniqueness
var array: [Int] = [] //Use arrays to guarantee the order
while randomSet.count < 2 {
randomSet.insert(Int(arc4random())) //Whatever random number generator you use
}
for number in randomSet {
array.append(number)
}
//Now you can use the array for your operations
这个怎么样:
let desired = 20
var randomSet: Set<Int> = [] //Sets guarantee uniqueness
var array: [Int] = [] //Use arrays to guarantee the order
while array.count < desired {
let random = Int(arc4random())
if !randomSet.contains(random) {
array.append(random)
randomSet.insert(random)
}
}
或者,使用 LeoDaubus 的建议:
while array.count < desired {
let random = Int(arc4random())
if randomSet.insert(random).inserted {
array.append(random)
}
}
您可以使用集合来检查是否插入了随机数,在检查是否插入后追加成员:
var set: Set<Int> = []
var randomElements: [Int] = []
let numberOfElements = 10
while set.count < numberOfElements {
let random = Int(arc4random_uniform(10)) // 0...9
set.insert(random).inserted ? randomElements.append(random) : ()
}
print(randomElements) // "[5, 2, 8, 0, 7, 1, 4, 3, 6, 9]\n"
我想使用 arc4random 但生成的数字必须彼此不同。
我如何做这个例子?
您可以使用 Set
轻松实现:
var randomSet: Set<Int> = [] //Sets guarantee uniqueness
var array: [Int] = [] //Use arrays to guarantee the order
while randomSet.count < 2 {
randomSet.insert(Int(arc4random())) //Whatever random number generator you use
}
for number in randomSet {
array.append(number)
}
//Now you can use the array for your operations
这个怎么样:
let desired = 20
var randomSet: Set<Int> = [] //Sets guarantee uniqueness
var array: [Int] = [] //Use arrays to guarantee the order
while array.count < desired {
let random = Int(arc4random())
if !randomSet.contains(random) {
array.append(random)
randomSet.insert(random)
}
}
或者,使用 LeoDaubus 的建议:
while array.count < desired {
let random = Int(arc4random())
if randomSet.insert(random).inserted {
array.append(random)
}
}
您可以使用集合来检查是否插入了随机数,在检查是否插入后追加成员:
var set: Set<Int> = []
var randomElements: [Int] = []
let numberOfElements = 10
while set.count < numberOfElements {
let random = Int(arc4random_uniform(10)) // 0...9
set.insert(random).inserted ? randomElements.append(random) : ()
}
print(randomElements) // "[5, 2, 8, 0, 7, 1, 4, 3, 6, 9]\n"