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
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.
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.
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)))))))