Created
September 1, 2015 21:55
-
-
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/
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
/*: | |
**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))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What do we do for Swift 3.0 if we use PermutationGenerator?