Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Last active April 5, 2017 21:17
Show Gist options
  • Select an option

  • Save natecook1000/ef096622dab1981823c5 to your computer and use it in GitHub Desktop.

Select an option

Save natecook1000/ef096622dab1981823c5 to your computer and use it in GitHub Desktop.

Revisions

  1. natecook1000 revised this gist Oct 13, 2015. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion shuffle.swift
    Original file line number Diff line number Diff line change
    @@ -2,7 +2,7 @@
    //
    // Fisher-Yates shuffle as protocol extensions

    extension CollectionType where Index == Int {
    extension CollectionType {
    /// Return a copy of `self` with its elements shuffled
    func shuffle() -> [Generator.Element] {
    var list = Array(self)
    @@ -19,6 +19,7 @@ extension MutableCollectionType where Index == Int {

    for i in 0..<count - 1 {
    let j = Int(arc4random_uniform(UInt32(count - i))) + i
    guard i != j else { continue }
    swap(&self[i], &self[j])
    }
    }
  2. natecook1000 created this gist Jun 30, 2015.
    35 changes: 35 additions & 0 deletions shuffle.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    // (c) 2015 Nate Cook, licensed under the MIT license
    //
    // Fisher-Yates shuffle as protocol extensions

    extension CollectionType where Index == Int {
    /// Return a copy of `self` with its elements shuffled
    func shuffle() -> [Generator.Element] {
    var list = Array(self)
    list.shuffleInPlace()
    return list
    }
    }

    extension MutableCollectionType where Index == Int {
    /// Shuffle the elements of `self` in-place.
    mutating func shuffleInPlace() {
    // empty and single-element collections don't shuffle
    if count < 2 { return }

    for i in 0..<count - 1 {
    let j = Int(arc4random_uniform(UInt32(count - i))) + i
    swap(&self[i], &self[j])
    }
    }
    }

    [1, 2, 3].shuffle()
    // [2, 3, 1]

    let fiveStrings = stride(from: 0, through: 100, by: 5).map(String.init).shuffle()
    // ["20", "45", "70", "30", ...]

    var numbers = [1, 2, 3, 4]
    numbers.shuffleInPlace()
    // [3, 2, 1, 4]