Skip to content

Instantly share code, notes, and snippets.

@scottrhoyt
Created September 1, 2015 21:55
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 scottrhoyt/3e877bb10fcc687f6068 to your computer and use it in GitHub Desktop.
Save scottrhoyt/3e877bb10fcc687f6068 to your computer and use it in GitHub Desktop.
This is a Swift 2.0 conversion of Erica Sadun's RandomGenerator from here: http://ericasadun.com/2015/04/24/swift-that-permutation-generator-thing/
/*:
**RandomGenerator.swift**
A Swift 2.0-compatible version of Erica Sadun's take on shuffling a
`CollectionType` available here:
http://ericasadun.com/2015/04/24/swift-that-permutation-generator-thing/.
*/
import Foundation
public struct RandomGenerator<C: CollectionType> : GeneratorType, SequenceType {
private var backingGenerator : PermutationGenerator<C, [C.Index]>
public init(_ elements : C) {
var indices = Array(elements.startIndex..<elements.endIndex)
for index in 0..<indices.count {
let swapIndex = index + Int(arc4random_uniform(UInt32(indices.count - index)))
if swapIndex != index {
swap(&indices[index], &indices[swapIndex])
}
}
backingGenerator = PermutationGenerator(elements: elements, indices: indices)
}
public typealias Element = C.Generator.Element
public typealias Generator = PermutationGenerator<C, [C.Index]>
public mutating func next() -> Element? {return backingGenerator.next()}
public func generate() -> PermutationGenerator<C, [C.Index]> {return backingGenerator}
}
let a = "πŸ˜€πŸ˜£πŸ˜¨πŸ˜­πŸ˜±πŸ˜·πŸ˜ΈπŸ˜½πŸ˜ΎπŸ‘£πŸ™€πŸ‘€πŸ˜“"
let b = "Hello There"
let c = [1, 2, 3, 4, 5, 6, 7, 8, 9]
let d = ["A":"B", "C":"D", "E":"F", "G":"H"]
let e = ["A":1, "B":2, "C":3, "D":4]
var f = Set(1...10)
print(Array(RandomGenerator(a.characters)))
print(Array(RandomGenerator(b.characters)))
print(Array(RandomGenerator(c)))
print(Array(RandomGenerator(d)))
print(Array(RandomGenerator(e)))
print(Array(RandomGenerator(f)))
@dndydon
Copy link

dndydon commented Apr 13, 2016

What do we do for Swift 3.0 if we use PermutationGenerator?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment