Created
April 24, 2015 20:22
-
-
Save erica/5820cb05acb58820ae37 to your computer and use it in GitHub Desktop.
Collection Randomizer
This file contains 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
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..<count(indices) { | |
var swapIndex = index + Int(arc4random_uniform(UInt32(count(indices) - 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) | |
println(Array(RandomGenerator(a))) | |
println(Array(RandomGenerator(b))) | |
println(Array(RandomGenerator(c))) | |
println(Array(RandomGenerator(d))) | |
println(Array(RandomGenerator(e))) | |
println(Array(RandomGenerator(f))) | |
Note: I used ContiguousArray
mostly for the heck of it. You can replace that with Array
if you feel like it. They should be basically the same thing when the element type isn't an obj-c class/protocol.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a version that should be more efficient. It uses the "inside-out" Fisher-Yates shuffle: