Generating Random non repeatable array in SWIFT
本问题已经有最佳答案,请猛点这里访问。
我想知道这一点,但是nsset(array:x).allobjects只能与[int]一起使用。
如何生成随机不可重复数组?
1 2 3 4 5 6 7 8 | 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) } |
首先,您必须将arc4random_uniform的结果转换为int:
1 | var draw = map(1...5) { _ in Int(arc4random_uniform(15))} |
号
然后,您需要创建一个while循环,该循环仅在nsset数组中包含的唯一元素数小于draw计数时执行。
1 2 3 4 5 6 7 8 9 10 | 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) |
你的要求不太清楚。
如果希望能够不重复地从数组中提取对象,请使用如下方法:
1 2 3 4 5 6 7 8 9 10 11 12 | 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)) } |
您可以调整上述方法来保存任何类型的对象的数组,或者将其更改为泛型,这样您就可以管理任何类型的对象的数组。