Created
December 15, 2017 15:57
-
-
Save keeferrourke/f3553c2209e7ec21915290dad669d97f to your computer and use it in GitHub Desktop.
This is a simple program to generate and print the binary reflected Gray code for n-digits. Supply "n" as the single argument when calling the program.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "log" | |
| "os" | |
| "strconv" | |
| ) | |
| func grayCode(seed []string, len int) []string { | |
| if len <= 1 { | |
| return seed | |
| } | |
| rev := reverse(seed, 0) | |
| var a, b []string | |
| for i := range seed { | |
| a = append(a, "0"+seed[i]) | |
| b = append(b, "1"+rev[i]) | |
| } | |
| code := append(reverse(a, 0), b...) | |
| return grayCode(code, len-1) | |
| } | |
| func reverse(s []string, start int) []string { | |
| for end := len(s) - 1; start < end; start, end = start+1, end-1 { | |
| s[start], s[end] = s[end], s[start] | |
| } | |
| return s | |
| } | |
| func main() { | |
| if len(os.Args) < 2 { | |
| log.Fatal("Invalid usage.") | |
| } | |
| n, err := strconv.Atoi(os.Args[1]) | |
| if err != nil { | |
| log.Fatal("%T: %v", err, err) | |
| } | |
| if n == 0 { | |
| log.Fatal("Integer must be greater than zero.") | |
| } | |
| seed := []string{"0", "1"} | |
| code := grayCode(seed, n) | |
| for _, v := range code { | |
| fmt.Println(v) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment