Permutation and list rotation

Here's an interesting implementation of a list permutation function, by Erik Naggum:

(defun permutations (list)
  (if (cdr list)
      (loop with rotation = list
          do (setq rotation (nconc (last rotation) (nbutlast rotation)))
          nconc (loop for list in (permutations (rest rotation))
                      collect (cons (first rotation) (copy-list list)))
          until (eq rotation list))
      (list list)))

The rotation trick with nconc/last/nbutlast/eq is new to me.

Tags:

Comments

August 2014

S M T W T F S
     12
3456789
10111213141516
17181920212223
24252627282930
31      
Powered by LiveJournal.com