How can I get all possible permutations of a list with Common Lisp?

后端 未结 3 1072
被撕碎了的回忆
被撕碎了的回忆 2021-02-08 11:01

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 ou

相关标签:
3条回答
  • 2021-02-08 11:37

    Walk through your list, selecting each element in turn. That element will be the first element of your current permutation.

    Cons that element to all permutations of the remaining elements.

    0 讨论(0)
  • 2021-02-08 11:39

    Here is the answer which allows repeated elements. The code is even more "lispish" as it doesn't use loop, with the disadvantage of being less comprehensible than Rainer Joswig's solution:

    (defun all-permutations (lst &optional (remain lst))
      (cond ((null remain) nil)
            ((null (rest lst)) (list lst))
            (t (append
                (mapcar (lambda (l) (cons (first lst) l))
                        (all-permutations (rest lst)))
                (all-permutations (append (rest lst) (list (first lst))) (rest remain))))))
    

    The optional remain argument is used for cdring down the list, rotating the list elements before entering the recursion.

    0 讨论(0)
  • 2021-02-08 11:42

    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)))))))
    
    0 讨论(0)
提交回复
热议问题