Skip to content

Instantly share code, notes, and snippets.

@kazk
Created December 29, 2014 21:16
Show Gist options
  • Save kazk/b1fb393e0bef772d988c to your computer and use it in GitHub Desktop.
Save kazk/b1fb393e0bef772d988c to your computer and use it in GitHub Desktop.
`roundRobin` function from D std.range in Swift.
// [roundRobin](http://dlang.org/phobos/std_range.html#roundRobin)
public func roundRobin<S:SequenceType>(sequences:S ...)
-> SequenceOf<S.Generator.Element>
{
func isDone(gs:[S.Generator?]) -> Bool {
for g in gs { if (g != nil) { return false } }
return true
}
return SequenceOf {_ -> GeneratorOf<S.Generator.Element> in
var generators:[S.Generator?] = sequences.map {$0.generate()}
let count = generators.count
var idx = 0
return GeneratorOf {
while !isDone(generators) {
if let r = generators[idx]?.next() {
idx = (idx + 1) % count
return r
}
generators[idx] = nil
idx = (idx + 1) % count
}
return nil
}
}
}
//roundRobin(
// [0, 3, 6],
// [1, 4, 7, 9],
// [2, 5, 8]).array //=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
public func roundRobinShortest<S:SequenceType>(sequences:S ...)
-> SequenceOf<S.Generator.Element>
{
return SequenceOf {_ -> GeneratorOf<S.Generator.Element> in
var generators:[S.Generator?] = sequences.map {$0.generate()}
let count = generators.count
var idx = 0
return GeneratorOf {
switch generators[idx]?.next() {
case .None: return nil
case .Some(let r):
idx = (idx + 1) % count
return r
}
}
}
}
//roundRobinShortest(
// [0, 3, 6],
// [1, 4, 7, 9],
// [2]).array //=>[0,1,2,3,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment