Skip to content

Instantly share code, notes, and snippets.

@digoreis
Created March 23, 2017 19:57
Show Gist options
  • Save digoreis/f7bff4a090e12462656a2da8544ff43e to your computer and use it in GitHub Desktop.
Save digoreis/f7bff4a090e12462656a2da8544ff43e to your computer and use it in GitHub Desktop.
RandomQueue
class RandomQueue<T> : IteratorProtocol {
typealias Element = T
var position = 0
var positions : [Int] = []
let items : [T]
init(items:[T]){
self.items = items
}
func next() -> T? {
guard positions.count != items.count else { return nil }
return items[random()]
}
fileprivate func random() -> Int {
var ranNumber : Int = 0
repeat {
ranNumber = Int(arc4random_uniform(UInt32(items.count)))
} while (positions.contains(ranNumber))
positions.append(ranNumber)
return ranNumber
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment