更快的排列生成器
我为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在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