[ create a new paste ] login | about

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

programmingpraxis - Scheme, pasted on Dec 1:
; gray code neighbors

(define (logand a b)
  (if (or (zero? a) (zero? b)) 0
    (+ (* (logand (floor (/ a 2)) (floor (/ b 2))) 2)
       (if (or (even? a) (even? b)) 0 1))))

(define (logxor a b)
  (cond ((zero? a) b)
        ((zero? b) a)
        (else
         (+ (* (logxor (floor (/ a 2)) (floor (/ b 2))) 2)
            (if (even? a)
                (if (even? b) 0 1)
                (if (even? b) 1 0))))))

(define (neighbors? a b)
  (let ((x (logxor a b)))
    (= (logand x (- x)) x)))

(display (neighbors? 88 72)) (newline) ; true, 16-bit
(display (neighbors? 88 89)) (newline) ; true, 1-bit
(display (neighbors? 88 90)) (newline) ; true, 2-bit
(display (neighbors? 88 91)) (newline) ; false, 1-bit and 2-bit


Output:
1
2
3
4
#t
#t
#t
#f


Create a new paste based on this one


Comments: