Skip to content

Instantly share code, notes, and snippets.

@ktprezes
Forked from kiwiandroiddev/CartesianProduct.kt
Created November 6, 2021 23:32
Show Gist options
  • Save ktprezes/b4cec5a418eb15e918f7fc9d9a064251 to your computer and use it in GitHub Desktop.
Save ktprezes/b4cec5a418eb15e918f7fc9d9a064251 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