更快的排列生成器

发布于 2024-10-10 11:14:24 字数 941 浏览 3 评论 0原文

我为 Scala 列表编写了一个排列生成器,它生成给定列表的所有排列。到目前为止,我基于 此 Haskell 实现 (而且我认为它比我尝试过的其他几个选项更有效)。有什么方法可以提高效率,或者我已经涵盖了所有基础吗?

   /** 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
   }

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
   }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

宫墨修音 2024-10-17 11:14:24

在Scala 2.9中,临时添加了一些有用的方法到scala集合类,包括一个Seq.permutations,它生成这个seq的所有排列。请参阅链接文本 。我有一个非递归实现,我认为它会有更好的性能。请参阅SeqLike.permutations 的非递归实现

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文