From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2003-07-20T01:50:43+09:00 Subject: Re: [SNIPPET] Binary counter In article , Simon Strandgaard <0bz63fz3m1qt3001@sneakemail.com> wrote: >On Sat, 19 Jul 2003 18:04:07 +0900, Brian Candler wrote: > >> On Sat, Jul 19, 2003 at 07:26:32AM +0900, Phil Tomson wrote: >>> You guys are spoiling all my fun with recursive functions ;-) >> >> Sorry. Well for a bit more fun, how about writing a Gray code counter? The >> characteristic of this sequence is that each number differs from the >> previous one by exactly one bit. > >I found a homepage: ruby + gray code > >http://www.public.asu.edu/~ncban/graycode.html > Very nice, compact algorithm there. "Here's an algorithm for translating binary to Gray code. It's in a loop here, but unlike the other algorithms we've looked at, it doesn't have to be. This algorithm can convert an arbitrary binary number to Gray code in finite time. Wonderful! #!/usr/bin/env ruby bits = 4 (1 << bits).times do |binary| grayCode = binary ^ (binary >> 1) printf "%0#{bits}b\n", grayCode end How does it work? Beats me. It's magic. " Phil