Last active
August 29, 2015 14:04
-
-
Save airspeedswift/34251f2ddb1b038c5d88 to your computer and use it in GitHub Desktop.
Every combination of every element of two sequences in Swift - ugly brute force version
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
// after https://twitter.com/cocoaphony/status/490708834415947776 | |
func combinations | |
<First: SequenceType, Second: CollectionType> | |
(first: First, second: Second) | |
-> GeneratorOf<(First.Generator.Element, Second.Generator.Element)> { | |
var first_gen = first.generate() | |
var second_gen = second.generate() | |
var current_first = first_gen.next() | |
return GeneratorOf { | |
// check if there's more of first to consume | |
if let this_first = current_first { | |
// if so, is there more of this go-around | |
// of second to consume? | |
if let this_second = second_gen.next() { | |
return (this_first, this_second) | |
} | |
// if second used up, reset it | |
else { | |
// go back to the beginning of second | |
second_gen = second.generate() | |
// and take the first element of it | |
let next_second = second_gen.next() | |
// was there a first element? | |
if let this_second = next_second { | |
// move on to the next element of first | |
current_first = first_gen.next() | |
// is there such an element? | |
if let this_first = current_first { | |
return (this_first, this_second) | |
} | |
// if not, we've reached the end of | |
// the first sequence | |
else { | |
// so we've finished | |
return nil | |
} | |
} | |
// if not, second is empty | |
else { | |
// so we need to guard against | |
// infinite looping in that case | |
return nil | |
} | |
} | |
} | |
// if not, we've reached the end of | |
// the first sequence | |
else { | |
// so we've finished | |
return nil | |
} | |
} | |
} | |
let combos = map(combinations("ABC", "123")) { [$0] + [$1] } | |
for c in combos { | |
println(c) | |
} | |
===> | |
A1 | |
A2 | |
A3 | |
B1 | |
B2 | |
B3 | |
C1 | |
C2 | |
C3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment