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

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

提交回复
热议问题