我怎样才能获得与Common Lisp的一个列表中的所有可能的排列?排列、列表中、Common、Lisp

2023-09-11 03:46:33 作者:帅气欧霸,萌萌海鸥?

我试图写一个Common Lisp的功能,这将使我一个列表的所有可能的排列,使用每个元素只有一次。例如,列表'(1 2 3)将得到的输出((1 2 3)(1 3 2)(2 1 3)(2 3 1)(3 1 2)(3 2 1))。

I'm trying to write a Common Lisp function that will give me all possible permutations of a list, using each element only once. For example, the list '(1 2 3) will give the output ((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1)).

我已经写的东西,那种作品,但它的笨重,它并不总是工作,我甚至不真正了解它。我不要求为code,说不定关于如何去想一些指导。我不知道很多关于编写算法。

I already wrote something that kind of works, but it's clunky, it doesn't always work and I don't even really understand it. I'm not asking for code, just maybe for some guidance on how to think about it. I don't know much about writing algorithms.

谢谢, 杰森

推荐答案

作为一个基本方法,所有排列遵循这个递归模式:

As a basic approach, "all permutations" follow this recursive pattern:


  all permutations of a list L is:
    for each element E in L:
      that element prepended to all permutations of [ L with E removed ]

如果我们把所给,你必须在你的列表中没有重复的元素,下面应该做的:

If we take as given that you have no duplicate elements in your list, the following should do:


(defun all-permutations (list)
  (cond ((null list) nil)
        ((null (cdr list)) (list list))
        (t (loop for element in list
             append (mapcar (lambda (l) (cons element l))
                            (all-permutations (remove element list)))))))
 
精彩推荐