Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1072588
  • 博文数量: 104
  • 博客积分: 3715
  • 博客等级: 中校
  • 技术积分: 1868
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-30 08:38
文章分类

全部博文(104)

文章存档

2013年(1)

2012年(9)

2011年(41)

2010年(3)

2009年(3)

2008年(47)

分类: Python/Ruby

2011-12-11 01:18:55

下午无聊,到论坛闲逛。发现一个朋友提到面试时的一个问题“打印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))))
阅读(1896) | 评论(1) | 转发(1) |
0

上一篇:Hive Internals PPT

下一篇:我的微博

给主人留下些什么吧!~~

鱼门客栈2011-12-12 23:36:29

到底是怎样找的?