Skip to content

Instantly share code, notes, and snippets.

@shawnsmithdev
Last active August 29, 2015 14:15
Show Gist options
  • Save shawnsmithdev/199ef28e06326d37bc8e to your computer and use it in GitHub Desktop.
Save shawnsmithdev/199ef28e06326d37bc8e to your computer and use it in GitHub Desktop.
reflect and prefix algorithm for gray codes
package main
import (
"fmt"
)
func main() {
gray(8)
}
func gray(bits uint) {
x := make([]uint64, 2, 1<<bits)
x[0] = 0
x[1] = 1
for prefixMask := uint64(2); prefixMask < (1 << bits); prefixMask <<= 1 {
y := x[:len(x)*2]
for idx := range x {
y[len(x)+idx] = x[len(x)-idx-1] | prefixMask
}
x = y
}
for idx, val := range x {
fmt.Printf("0x%02X: %08b\n", idx, val)
}
}
@shawnsmithdev
Copy link
Author

0x00: 00000000
0x01: 00000001
0x02: 00000011
0x03: 00000010
0x04: 00000110
0x05: 00000111
0x06: 00000101
0x07: 00000100
0x08: 00001100
0x09: 00001101
0x0A: 00001111
0x0B: 00001110
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment