Skip to content

Instantly share code, notes, and snippets.

@airspeedswift
Created April 4, 2015 22:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airspeedswift/03d07a9dc86fabdc370f to your computer and use it in GitHub Desktop.
Save airspeedswift/03d07a9dc86fabdc370f to your computer and use it in GitHub Desktop.
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