Last active
March 5, 2020 10:27
-
-
Save turtlemonvh/48ea49a3e7d0ae3971719acf553ccb45 to your computer and use it in GitHub Desktop.
Scala cartesian product
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
// 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)))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On Stackoverflow: https://stackoverflow.com/a/50105448/790075