Skip to content

Instantly share code, notes, and snippets.

@turtlemonvh
Last active March 5, 2020 10:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turtlemonvh/48ea49a3e7d0ae3971719acf553ccb45 to your computer and use it in GitHub Desktop.
Save turtlemonvh/48ea49a3e7d0ae3971719acf553ccb45 to your computer and use it in GitHub Desktop.
Scala cartesian product
// Based on: http://thushw.blogspot.com/2015/10/cartesian-product-in-scala.html
package com.github.turtlemonvh.helpers
object SequenceHelpers {
/* Take a list of lists and return a list of lists that is the cartesian product of the members if each list.
val seqs = List(List("1", "2", "3"), List("a", "b", "c", "d"), List("true", "false"))
// 24 = (3 * 4 * 2)
cartesianProduct[String](seqs).length
*/
def cartesianProduct[T](seqs: Seq[Seq[T]]): Seq[Seq[T]] = {
seqs.foldLeft(Seq(Seq.empty[T]))((b, a) => b.flatMap(i => a.map(j => i ++ Seq(j))))
}
}
@turtlemonvh
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment