下午无聊,到论坛闲逛。发现一个朋友提到面试时的一个问题“打印A、B、C、D、E的所有排列组合”,一时手痒,就写了一个。内存占用有些大,不过这个好说,只要将生成排列的结果用stream表示就可以了,stream是按需求值的,或者说惰性求值的。代码如下:
- #lang racket/base
-
-
;; get all permutations of [0 .. (- n 1)],
-
;; return as a list
-
(define (permutation n)
-
;; get all permutations of [0 .. (- i 1), (+ i 1) .. (- n 1)]
-
;; return as a list
-
(define (permutation/without i n)
-
(let ((temp-last (- n 1)))
-
(map (lambda (temp-permutation)
-
(map (lambda (x)
-
(if (eqv? x i)
-
temp-last
-
x))
-
temp-permutation))
-
(permutation temp-last))))
-
-
(if (or (= n 1) (< n 1)) ;; base case
-
'((0))
-
(for/fold ((result '())) ((i n))
-
(foldl (lambda (irest result)
-
(cons (cons i irest)
-
result))
-
result
-
(permutation/without i n)))))
-
-
;; print out all the permutations of ABCDE
-
(define (print-result)
-
(let ((elements #(A B C D E)))
-
(for-each (lambda (indexes)
-
(for-each (lambda (i)
-
(printf "~a" (vector-ref elements i)))
-
indexes)
-
(printf "~n"))
-
(permutation 5))))
阅读(1975) | 评论(1) | 转发(1) |