在 SWIFT 中生成随机不可重复数组

Generating Random non repeatable array in SWIFT

我正在尝试解决这个问题,但 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)
}

你问的不是很清楚

如果您希望能够从数组中取出对象而不重复,请使用如下方式:

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))
}

您可以采用上述方法来保存任何类型对象的数组,或将其更改为泛型,以便您可以管理任何类型对象的数组。

首先你必须将结果从 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)