Last active
April 13, 2017 00:33
-
-
Save WikipediaBrown/5a2833f1d5f24ebacd7f1be96dd38a3d to your computer and use it in GitHub Desktop.
This is an implementation of the Fisher-Yates shuffling algorithm in Swift as modernized by Richard Durstenfeld.
This file contains hidden or 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
//# Fisher-Yates Shuffle | |
//## Implemented in Swift | |
//This is an implementation of the Fisher-Yates shuffling algorithm as modernized by Richard Durstenfeld. His version shuffles the collection in place. This implementation is based on the psuedo-code used to describe the algorithm at [Wikipedia](https://en.m.wikipedia.org/wiki/Fisher–Yates_shuffle#The_modern_algorithm). Here, we extend the Array struct with a ```shuffle()``` function. With this extension, we can quickly and uniformly shuffly any array (no matter the elements) in O(n) time. | |
// From Wikipedia/n | |
//>The Fisher–Yates shuffle is an algorithm for generating a random permutation of a finite set—in plain terms, the algorithm shuffles the set. The algorithm effectively puts all the elements into a hat; it continually determines the next element by randomly drawing an element from the hat until no elements remain. The algorithm produces an unbiased permutation: every permutation is equally likely. The modern version of the algorithm is efficient: it takes time proportional to the number of items being shuffled and shuffles them in place. | |
// | |
//>The Fisher–Yates shuffle is named after Ronald Fisher and Frank Yates, who first described it, and is also known as the Knuth shuffle after Donald Knuth. A variant of the Fisher–Yates shuffle, known as Sattolo's algorithm, may be used to generate random cyclic permutations of length n instead of random permutations. | |
//> - Wikipedia | |
import Foundation | |
extension Array { | |
mutating func shuffle() { | |
guard count > 1 else {return} | |
for shufflingIndex in (1..<count).reversed() { | |
let randomIndex = Int(arc4random_uniform(UInt32(shufflingIndex))) | |
swap(&self[shufflingIndex], &self[randomIndex]) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fisher-Yates Shuffle
Implemented in Swift
This is an implementation of the Fisher-Yates shuffling algorithm as modernized by Richard Durstenfeld. This implementation is based on the psuedo-code used to describe the algorithm at Wikipedia. Here, we extend the Array struct with a
shuffle()
function. With this extension, we can quickly and uniformly shuffly any array (no matter the elements) in O(n) time.From Wikipedia/n