Skip to content

Instantly share code, notes, and snippets.

@adamretter
Created May 28, 2014 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamretter/ddc675d7cd27fb32453a to your computer and use it in GitHub Desktop.
Save adamretter/ddc675d7cd27fb32453a to your computer and use it in GitHub Desktop.
All permutations of all combinations of input
object AllCombinations extends App {
/**
* Returns all permutations of all combinations
* of everything in the input data
*
* For example, given the `data` List('a', 'b', 'c')
* will return the result:
*
* List(
* List(a),
* List(b),
* List(c),
* List(a, b),
* List(b, a),
* List(a, c),
* List(c, a),
* List(b, c),
* List(c, b),
* List(a, b, c),
* List(a, c, b),
* List(b, a, c),
* List(b, c, a),
* List(c, a, b),
* List(c, b, a)
* )
*
* @param data The input data to calculate all permutations of
*
* @return All permutations of all combinations of the input data
*/
def allCombinations[T](data: List[T]) : List[List[T]] = {
(for(i <- 1 to data.length) yield
data.combinations(i).toList.map(_.permutations.toList).flatten
).toList.flatten
}
//example use
val stuff = List('a', 'b', 'c')
for(x <- allCombinations(stuff))
println(x)
}
@soc
Copy link

soc commented May 28, 2014

Slightly simplified:

def allCombinations[T](data: List[T]): List[List[T]] = (
  for(i <- 1 to data.length)
  yield data.combinations(i).flatMap(_.permutations)).toList.flatten

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