I've written a permutation generator for Scala lists that generates all permutations of a given list. So far, I've got the following based on this Haskell implementation (and I think it's more efficient than several other options I've tried). Are there any ways to make this even more efficient, or have I covered all my bases?
/** For each element x in List xss, returns (x, xss - x) */
def selections[A](xss:List[A]):List[(A,List[A])] = xss match {
case Nil => Nil
case x :: xs =>
(x, xs) :: (for( (y, ys) <- selections (xs) )
yield (y, x :: ys))
}
/** Returns a list containing all permutations of the input list */
def permute[A](xs:List[A]):List[List[A]] = xs match {
case Nil => List(Nil)
//special case lists of length 1 and 2 for better performance
case t :: Nil => List(xs)
case t :: u :: Nil => List(xs,List(u,t))
case _ =>
for ( (y,ys) <- selections(xs); ps <- permute(ys))
yield y :: ps
}
Heap's algorithm is used to generate all permutations of n objects. The idea is to generate each permutation from the previous permutation by choosing a pair of elements to interchange, without disturbing the other n-2 elements. Following is the illustration of generating all the permutations of n given numbers.
The Excel PERMUT function returns the number of permutations (combinations where order is significant) for a given number of items. The PERMUT function does not allow repetitions. To allow permutations with repetitions, use the PERMUTATIONA function.
In Scala 2.9 extempore have added some useful methods to scala collection class, include a Seq.permutations which generating all permutations of this seq. See link text. And I have a non-recursive implementation which I think would have a better performance. See A non-recursive implementation of SeqLike.permutations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With