Skip to content

Instantly share code, notes, and snippets.

@iamtomcat
Forked from natecook1000/shuffle.swift
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamtomcat/cc8cc8777d4c3ae4145f to your computer and use it in GitHub Desktop.
Save iamtomcat/cc8cc8777d4c3ae4145f to your computer and use it in GitHub Desktop.
// (c) 2014 Nate Cook, licensed under the MIT license
//
// Fisher-Yates shuffle as top-level functions and array extension methods
/// Shuffle the elements of `list`.
func shuffle<C: MutableCollectionType where C.Index == Int>(inout list: C) {
let count = countElements(list)
for i in 0..<(count - 1) {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
swap(&list[i], &list[j])
}
}
/// Return a collection containing the shuffled elements of `list`.
func shuffled<C: MutableCollectionType where C.Index == Int>(var list: C) -> C {
shuffle(&list)
return list
}
extension Array {
/// Shuffle the elements of `self` in-place.
mutating func shuffle() {
for i in 0..<(count - 1) {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
swap(&self[i], &self[j])
}
}
/// Return a copy of `self` with its elements shuffled
func shuffled() -> [T] {
var list = self
list.shuffle()
return list
}
}
// Example of global functions
var strings = ["one", "two", "three", "four", "five", "six"]
shuffle(&strings)
// e.g., strings == [four, six, three, two, five, one]
let shuffledStrings = shuffled(strings)
// e.g., shuffledStrings == [six, four, one, five, three, two]
// Example of array methods
var numbers = [1, 2, 3, 4, 5, 6, 7, 8]
numbers.shuffle()
// e.g., numbers == [6, 1, 8, 3, 2, 4, 7, 5]
let shuffledNumbers = numbers.shuffled()
// e.g., mixedup == [4, 2, 6, 8, 7, 3, 5, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment