Last active
October 8, 2017 20:02
-
-
Save robertmryan/b002b7d524646fd677bb3979c89ec331 to your computer and use it in GitHub Desktop.
Shuffle: Fisher-Yates vs Naive Shuffles (Swift 4)
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
extension Array { | |
/// Simple implementation of Fisher-Yates | |
mutating func shuffle() { | |
for i in 0 ..< count - 1 { | |
let j = i + Int(arc4random_uniform(UInt32(count - i))) | |
swapAt(i, j) | |
} | |
} | |
/// Naive implementation that introduces biases | |
mutating func shuffleBiased() { | |
for i in 0 ..< count { | |
let j = Int(arc4random_uniform(UInt32(count))) | |
swapAt(i, j) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pursuant to https://stackoverflow.com/questions/46615663/shuffle-an-array