Introduction
This code was part of one of my projects where it was used to generate boolean input values for truth tables. I have since generalized it for combinations of variables with only 2 values, and added a dash of general Scala-isms. This has been unit-tested with ScalaTest, and has proper documentation.
I rewrote my original code which used bitmasking and shifts because I thought it was too "magical", i.e., difficult to understand at first glance. The bitmasking method also does not give a proper ordering of the values as I would have liked it, which this method does.
This also embodies the concept of a multi-line expression-bodied method.
Notes
My IDE (IntelliJ Idea) recommends not using superfluous parentheses, but I leave them in for clarity.
I would like reviews on any and all aspects of the code and documentation, including but not limited to performance (not really important over clarity to me here, otherwise I'd have used the bitmasking version instead), clarity and idiomatic nature of the code.
Running
Just copy into a file with extension .scala
and run it in the Scala REPL as a script. Example usage:
allCombinations(4, true, false) // duplicates the use case I had in my project.
(Run the above in the REPL after the script as beem loaded (scala <file name>.scala
, or put it at the bottom of the file <file name>.scala
)
Code
/**
* Generates all possible distinct combinations of `n` variables which have only 2 values,
* `value` and `alternativeValue`.
*
* @param n the number of variables to generate combinations for
* @param value one possible value for a variable
* @param alternativeValue the other possible value for a variable
* @return all possible distinct combinations of `n` booleans
*/
def allCombinations[T](n: Int, value: T, alternativeValue: T): Seq[Seq[T]] = {
for (i <- 0 to n) yield {
// Make the first i values true and the rest false,
// and then take all their permutations.
// This gives us all the required combinations.
(Seq.tabulate(n)(x =>
if (x < i) value
else alternativeValue)
).permutations
} // flatten 1 level into a 1-deep list
}.flatten