Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fisher-Yates Shuffle in Swift 1.2
import Darwin
func shuffle<C: MutableCollectionType where C.Index.Distance == Int>(var list: C) -> C {
var n = count(list)
if n == 0 { return list }
let oneBeforeEnd = advance(list.startIndex, n.predecessor())
for i in list.startIndex..<oneBeforeEnd {
let ran = Int(arc4random_uniform(UInt32(n--)))
let j = advance(i,ran)
swap(&list[i], &list[j])
}
return list
}
shuffle([] as [Int])
shuffle([1] as [Int])
shuffle(Array(1...5) as [Int])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.