I coded a function to enumerate all permutations of a given list. What do you think of the code below?
def interleave(x:Int, l:List[Int]):List[List[Int]] = {
l match {
case Nil => List(List(x))
case (head::tail) =>
(x :: head :: tail) :: interleave(x, tail).map(head :: _)
}
}
def permutations(l:List[Int]):List[List[Int]] = {
l match {
case Nil => List(List())
case (head::tail) =>
for(p0 <- permutations(tail); p1 <- interleave(head, p0)) yield p1
}
}
Given a Seq, one can already have permutations by invoking the
permutationsmethod.Furthermore there is also a method for
combinations:Regarding your implementation I would say three things:
(1) Its good looking
(2) Provide an iterator (which is the std collections approach that allows to discard elements). Otherwise, you can get lists with 1000! elements which may not fit in memory.
(3) You should remove duplicated permutations (as observed by Luigi), since :