Created
March 23, 2017 19:57
-
-
Save digoreis/f7bff4a090e12462656a2da8544ff43e to your computer and use it in GitHub Desktop.
RandomQueue
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
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