Skip to content

Instantly share code, notes, and snippets.

@dyoo
Created November 23, 2012 00:17
Show Gist options
  • Save dyoo/4133419 to your computer and use it in GitHub Desktop.
Save dyoo/4133419 to your computer and use it in GitHub Desktop.
Gray binary codes
#lang racket/base
;; Gray binary code, from TAOCP 7.2.1.1.
;;
;; Gray codes are sequences where adjacent elements are different in only one position.
;;
;; The gray codes of length n can be generated with the following recursive rules:
;;
;; G_0 = epsilon
;; G_{n+1} = 0 G_n, 1 ((G_n)^r)
;;
;; where ^r is notation for sequence reversal.
;;
;; Let's write this in code.
;; gamma: number -> (listof string)
(define (gamma n)
(cond
[(= n 0)
(list "")]
[else
(define gamma_n-1 (gamma (sub1 n)))
(append (for/list ([s gamma_n-1])
(string-append "0" s))
(for/list ([s (reverse gamma_n-1)])
(string-append "1" s)))]))
;; For example:
(gamma 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment