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

后端 未结 3 1074
被撕碎了的回忆
被撕碎了的回忆 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: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)))))))
    

提交回复
热议问题