Skip to content

Instantly share code, notes, and snippets.

@kiwiandroiddev
Created August 23, 2019 01:58
Show Gist options
  • Save kiwiandroiddev/fef957a69f91fa64a46790977d98862b to your computer and use it in GitHub Desktop.
Save kiwiandroiddev/fef957a69f91fa64a46790977d98862b to your computer and use it in GitHub Desktop.
Kotlin function to return the cartesian product of two collections
/**
* E.g.
* cartesianProduct(listOf(1, 2, 3), listOf(true, false)) returns
* [(1, true), (1, false), (2, true), (2, false), (3, true), (3, false)]
*/
fun <T, U> cartesianProduct(c1: Collection<T>, c2: Collection<U>): List<Pair<T, U>> {
return c1.flatMap { lhsElem -> c2.map { rhsElem -> lhsElem to rhsElem } }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment