Skip to content

Instantly share code, notes, and snippets.

@bkyrlach
Created July 26, 2012 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bkyrlach/3184608 to your computer and use it in GitHub Desktop.
Save bkyrlach/3184608 to your computer and use it in GitHub Desktop.
Permutations of a list...
object P26 extends App {
def combinations[T](n: Int, l: List[T]): List[List[T]] = {
if(l.size < n) {
Nil
} else {
n match {
case 0 => Nil
case 1 => l.map{List(_)}
case _ => combinations(n-1,l.tail).map{ l.head :: _} ::: combinations(n, l.tail)
}
}
}
println(combinations(3, List('a, 'b, 'c, 'd, 'e, 'f)))
}
//Output:
// List(List('a, 'b, 'c), List('a, 'b, 'd), List('a, 'b, 'e), List('a, 'b, 'f), List('a, 'c, 'd), List('a, 'c, 'e), List('a, 'c, 'f), List('a, 'd, 'e), List('a, 'd, 'f), List('a, 'e, 'f), List('b, 'c, 'd), List('b, 'c, 'e), List('b, 'c, 'f), List('b, 'd, 'e), List('b, 'd, 'f), List('b, 'e, 'f), List('c, 'd, 'e), List('c, 'd, 'f), List('c, 'e, 'f), List('d, 'e, 'f))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment