Add procedure to do permutation, for example:
authorLi Qun <qun.li@uestcmail.com>
Tue Jul 22 22:17:22 2008 +0800 (2 years ago)
changeset 35f1d96bf11d9a
parent 341475fc7cdec5
child 361101e091e5cc
Add procedure to do permutation, for example:
> (permutation '(a b))
((b a) (a b))
src/scheme/L-99.scm
       1 --- a/src/scheme/L-99.scm	Tue Jul 22 17:20:03 2008 +0800
       2 +++ b/src/scheme/L-99.scm	Tue Jul 22 22:17:22 2008 +0800
       3 @@ -486,3 +486,26 @@
       4  		   (iter num (cdr lst) sublist)))))
       5  
       6    (iter num lst '()))
       7 +
       8 +;; Generate a permutation of a list.
       9 +;;
      10 +;; > Example:
      11 +;; (permutation '(a b c))
      12 +;; ((a b c) (a c b) (b a c) (b c a) (c a b) (c b a))
      13 +
      14 +;; P(n) = n * P(n - 1)
      15 +;; P(1) = 1
      16 +;; P(0) = 1
      17 +
      18 +(define (permutation lst)
      19 +  (define (iter lst sublist)
      20 +    (if (null? (cdr lst))
      21 +	(list (append sublist lst))
      22 +	(let loop ((idx (element-num lst)))
      23 +	  (if (> idx 0)
      24 +	      (append (iter (remove-at lst idx)
      25 +			    (cons (element-at lst idx) sublist))
      26 +		      (loop (- idx 1)))
      27 +	      '()))))
      28 +
      29 +  (if (null? lst) '() (iter lst '())))