我试图找出这个,但是NSSet(array:x).allObjects只适用于[Int]。
如何生成随机不可重复数组?
var x = map(1...5) { _ in arc4random_uniform(15)}
let xNonRepating = NSSet(array: x).allObjects
if x.count != xNonRepating.count {
//do nothing
} else {
x = map(1...5) { _ in arc4random_uniform(15)}
println(x)
}
答案 0 :(得分:0)
你的要求并不是很清楚。
如果您希望能够从没有重复的数组中获取对象,请使用以下内容:
var seedArray = ["one", "two", "three", "four", "five"]
var randomArray = Array()
func randomString -> String
{
if randomArray.count = 0
{
randomArray += seedArray
}
return randomArray.removeAtIndex(arc4random_uniform(randomArray.count))
}
您可以调整上述方法来保存任何类型对象的数组,或将其更改为通用对象,以便您可以管理任何类型对象的数组。
答案 1 :(得分:0)
首先,您必须将arc4random_uniform的结果转换为Int:
var draw = map(1...5) { _ in Int(arc4random_uniform(15))}
然后,您需要创建一个while循环,只有在NSSet数组中包含的唯一元素数小于绘制计数时才会执行。
var badDrawCounter = 0
while NSSet(array: draw).count < draw.count {
//it will only enter here if there was a repeated number in your draw
badDrawCounter++
println("bad draw = \(draw)")
// lets draw it again and if the result is not ok it will stay looping until you get a good draw (no repeating numbers)
draw = map(1...5) { _ in Int(arc4random_uniform(15))}
}
println(draw)