Created
April 4, 2015 22:06
-
-
Save airspeedswift/03d07a9dc86fabdc370f to your computer and use it in GitHub Desktop.
Fisher-Yates Shuffle in Swift 1.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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