Why is the function named allCombinations
? The "all" seems superfluous. Also, it's actually returning permutations rather than combinations, so the second half isn't really accurate either. I suggest naming it something else entirely, though: product
, based on the function in Python's itertools
module that does something similar. As for the first parameter, I find dims
(or dimensions
) to be more descriptive than n
.
Why limit yourself to two possible values? Why not also support a tri-state, for example? You could make values
variadic. As a bonus, you wouldn't have to manually toggle between value
and alternativeValue
; you could just use normal iteration tools like .map
.
def product[T](dims: Int, values: T*): Seq[Seq[T]] = {
dims match {
case 0 => Seq()
case 1 => values.map(Seq(_))
case _ => values.flatMap(v{
=> val lesserProduct = product(dims - 1, values:_*)
values.flatMap(v => lesserProduct.map(_.+:(v)))
}
}
}
Note that the ordering convention is different from yours; i.e. product(4, false, true)
is equivalent to allCombinations(4, true, false)
. I don't consider that to be a drawback.