我认为您只是想随机排列一些数字。我为 Swift 2.0 beta 6 制作了这个:
func randomUpTo(n: Int) -> Int {
return Int(arc4random_uniform(UInt32(n)))
}
extension CollectionType {
func shuffled() -> [Generator.Element] {
var ind = Array(indices)
return (startIndex..<endIndex).map{_ in self[ind.removeAtIndex(randomUpTo(ind.count))] }
}
}
你可以这样使用:
(1...100).shuffled() // [9, 8, 1, 19, 17, 2, 13, 16, 11, 12, 7, 14, 20, 3, 15, 6, 18, 4, 10, 5]
let alphabet = (1...26).map{ Character(UnicodeScalar($0 + 64)) } // ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
alphabet.shuffled() // ["V", "I", "S", "R", "H", "L", "F", "U", "T", "A", "X", "W", "B", "P", "K", "M", "Y", "E", "N", "Z", "G", "J", "Q", "D", "C", "O"]
编辑:上面的算法不如这个算法快(复杂度 O(n^2))(Fisher-Yikes 算法):
extension CollectionType {
func chooseRandom(n : Int = Int.max) -> [Generator.Element] {
var values = Array(self)
for index in values.indices.dropFirst().reverse().prefix(n) {
swap(&values[randomUpTo(index)], &values[index])
}
return Array(values.suffix(n))
}
}
你可以这样使用它:
(0...20).chooseRandom(10) // [20, 8, 7, 12, 3, 10, 19, 2, 15, 16]
[1, 3, 5, 7, 9, 11].chooseRandom() // [11, 9, 3, 1, 7, 5]
它适用于任何CollectionType。复杂度为 O(n)