Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.