Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster permutation generator

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
   }
like image 293
Ken Bloom Avatar asked Jan 04 '11 17:01

Ken Bloom


People also ask

How do you generate all permutations efficiently?

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.

Can Excel do permutations?

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.


1 Answers

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

like image 118
Eastsun Avatar answered Oct 01 '22 08:10

Eastsun