Combinations and Permutations
Posted: Wed Mar 02, 2005 7:58 pm
Has anyone written any programs that will take a list of items and return the list of lists of the combinations/permutations of n items taken r at a time?
Friends and Fans of newLISP
http://www.newlispfanclub.alh.net/forum/
http://www.newlispfanclub.alh.net/forum/viewtopic.php?f=5&t=553
Code: Select all
;;
;; Warren-Hanson algorithm for generating permutations of
;; multisets.
;;
> (defun make-k-permutations (k multiset)
(let ((pivots (remove-duplicates multiset)))
(if (= k 1)
(mapcar #'list pivots)
(let ((acc '()))
(dolist (p pivots acc)
(let ((sub-multiset (remove p multiset :count 1)))
(dolist (sub-perm (make-k-permutations
(1- k)
sub-multiset))
(push (cons p sub-perm) acc))))))))
MAKE-K-PERMUTATIONS
> (setq M1 '(93 4 42 93 5 7 8 10 8 8 10 42 4))
(93 4 42 93 5 7 8 10 8 8 10 42 4)
> (make-k-permutations 2 M1)
((4 4) (4 42) (4 10) (4 8) (4 7) (4 5) (4 93) (42 4) (42 42)
(42 10) (42 8) (42 7) (42 5) (42 93) (10 4) (10 42) (10 10)
(10 8) (10 7) (10 5) (10 93) (8 4) (8 42) (8 10) (8 8) (8 7)
(8 5) (8 93) (7 4) (7 42) (7 10) (7 8) (7 5) (7 93) (5 4) (5 42)
(5 10) (5 8) (5 7) (5 93) (93 4) (93 42) (93 10) (93 8) (93 7)
(93 5) (93 93))
Code: Select all
;;
;; Warren-Hanson algorithm for generating permutations of
;; multisets. - modified for newLISP
;;
;;
(define (make-k-p k multiset)
(let ((pivots (unique multiset)))
(if (= k 1)
(map list pivots)
(let ((acc '()))
(dolist (p pivots)
(let ((sub-multiset (replace p multiset)))
(dolist (sub-perm (make-k-p (- k 1) sub-multiset))
(push (cons p sub-perm) acc)))) acc) )))
Code: Select all
(setq M '(93 4 42 93 5 7 8 10 8 8 10 42 4))
Code: Select all
(define (make-k-permutations k multiset)
(let ((pivots (unique multiset)))
(if (= k 1)
(map list pivots)
(let ((acc '()))
(dolist (p pivots)
(let ((sub-multiset (remove1 p multiset)))
(dolist (sub-perm
(make-k-permutations (- k 1) sub-multiset))
(push (cons p sub-perm) acc))))
acc))))
(define (remove1 elt lst)
(let ((elt-pos (find elt lst)))
(if elt-pos (pop lst elt-pos))
lst))