[ create a new paste ] login | about

Link: http://codepad.org/ndutMKZE    [ raw code | output | fork ]

programmingpraxis - Scheme, pasted on Apr 28:
; binary reflected gray code

(define (ash int cnt)
  (if (negative? cnt)
      (let ((n (expt 2 (- cnt))))
        (if (negative? int)
            (+ -1 (quotient (+ 1 int) n))
            (quotient int n)))
      (* (expt 2 cnt) int)))

(define (gray n)
  (define (add x) (lambda (y) (+ x y)))
  (let loop ((n n) (g 1) (gs (list 0)))
    (if (zero? n) gs
      (loop (- n 1) (+ g g)
            (append gs (map (add g) (reverse gs)))))))

(display (gray 0)) (newline)
(display (gray 1)) (newline)
(display (gray 2)) (newline)
(display (gray 3)) (newline)
(display (gray 4)) (newline)
(display (gray 5)) (newline)

(define (nth-gray n) (bitwise-xor n (ash n -1)))

(display (nth-gray 0)) (newline)
(display (nth-gray 1)) (newline)
(display (nth-gray 2)) (newline)
(display (nth-gray 3)) (newline)
(display (nth-gray 4)) (newline)
(display (nth-gray 5)) (newline)
(display (nth-gray 6)) (newline)
(display (nth-gray 7)) (newline)
(display (nth-gray 8)) (newline)
(display (nth-gray 9)) (newline)


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
(0)
(0 1)
(0 1 3 2)
(0 1 3 2 6 7 5 4)
(0 1 3 2 6 7 5 4 12 13 15 14 10 11 9 8)
(0 1 3 2 6 7 5 4 12 13 15 14 10 11 9 8 24 25 27 26 30 31 29 28 20 21 23 22 18 19 17 16)
0
1
3
2
6
7
5
4
12
13


Create a new paste based on this one


Comments: