找出一组对象所有的全排列

807阅读 0评论2011-12-12 鱼门客栈
分类:

下午无聊,到论坛闲逛。发现一个朋友提到面试时的一个问题“打印A、B、C、D、E的所有排列组合”,一时手痒,就写了一个。内存占用有些大,不过这个好说,只要将生成排列的结果用stream表示就可以了,stream是按需求值的,或者说惰性求值的。代码如下:
  1. #lang racket/base

  2. ;; get all permutations of [0 .. (- n 1)],
  3. ;; return as a list
  4. (define (permutation n)
  5.   ;; get all permutations of [0 .. (- i 1), (+ i 1) .. (- n 1)]
  6.   ;; return as a list
  7.   (define (permutation/without i n)
  8.     (let ((temp-last (- n 1)))
  9.       (map (lambda (temp-permutation)
  10.              (map (lambda (x)
  11.                     (if (eqv? x i)
  12.                         temp-last
  13.                         x))
  14.                   temp-permutation))
  15.            (permutation temp-last))))

  16.   (if (or (= n 1) (< n 1)) ;; base case
  17.       '((0))
  18.       (for/fold ((result '())) ((i n))
  19.         (foldl (lambda (irest result)
  20.                      (cons (cons i irest)
  21.                            result))
  22.                result
  23.                (permutation/without i n)))))

  24. ;; print out all the permutations of ABCDE
  25. (define (print-result)
  26.   (let ((elements #(A B C D E)))
  27.     (for-each (lambda (indexes)
  28.                 (for-each (lambda (i)
  29.                             (printf "~a" (vector-ref elements i)))
  30.                           indexes)
  31.                 (printf "~n"))
  32.               (permutation 5))))
上一篇:LAMP编译安装
下一篇:informix chunk状态问题归纳