4 ms·
I'd recommend reading Knuth's TAOCP. Example: Knuth introduces the Grey code permutation of the natural numbers in The Art of Computer Programming, Volume 4 F
by erdos2 19y ago
I'd recommend reading Knuth's TAOCP.
Example: Knuth introduces the Grey code permutation of the natural numbers in The Art of Computer Programming, Volume 4 Fascicle 2, Generating All Tuples and Permutations (2005). Knuth gives the following equations defining Grey code sequences of length 2^n
G_0 = () [the empty list]
G_{n+1} = 0G_n 1G_n^R
where 0G_n means prepend 0 to everything in the list G_n,
and G_n^R means reverse the list G_n, and juxtaposition is concatenation of sequences. Successive elements of the list differ in precisely one bit position: this is obvious inductively, since if G_n does, so do 0G_n and 1G_n^R, and since the last element of G_n is the first element of G_n^R, the last element of 0G_n differs from the first element of 1G_n^R in the first digit. So this is a Grey code.
We get
G_0 = ()
G_1 = (0 1)
G_2 = (00 01 11 10)
G_3 = (000 001 011 010 110 111 101 100)
...
The sequence of G_n's induces a map g:N-->N
recursively by
g(0) = 0
g(k) = 2^n + g(2^n -1 - r)
for k = 2^n + r with 0≤r<2^n,
Here's an algorithm in Lisp for the function g.
The function MSB below kills off everything but the high-order bit of the binary representation of a non-negative integer.
(DEFUN MSB (n)
(LET (( x (LOGAND (- n 1 ) n)))
(COND ((EQUAL x 0) n)
(T (MSB x)))))
The MSB can be used to compute the Grey permutation
GREY:N-->N
(DEFUN GREY (n)
(COND
((= n 0) 0)
((= n 1) 1)
(T (LET ((x (MSB n))) (+ x (GREY (- (- x 1) (- n x))))))))
Restricting the domain and range of the GREY map to [0, 2^n -1] is a (well-defined) permutation; for example:
CL-USER> (MAPCAR #'GREY '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15))
(0 1 3 2 6 7 5 4 12 13 15 14 10 11 9 8)
And for fun, in my CMU common lisp system (under SLIME,
the Superior Lisp Interpretation Mode for Emacs):
CL-USER> (GREY 192873918237981273981279381729837127365712653712301098
102938891278389123112340983748920192834783201982374839201293874839201
982374893029872839409281729304983729102983748937291802357893465475648
576478658379128347635847658376485736451056105616516506105874568365836
503856836487134783748374817302893017308238713702873028730817387283462
864875387568475683756837458476583765847658376583746583764857364857638
4756387465837465917594857)
286196834290309414650371370191599291822213999612489335464107566352602
435648412184492184118063912008181215334900454318743739932993272952760
387272995403870156929179002537545706221256001587464111519239740005353
408236614872495338180309330035229762434762038407959020204331793558334
836843659189298641925497207483471043513624920173604726882678415424392
178475727939609277383096934996157278859779639219997432292981867624407
5270836893
Much larger numbers can be handled.