-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #310 from vaskoz/day148
Day148
- Loading branch information
Showing
3 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
package day148 | ||
|
||
import "fmt" | ||
|
||
// GrayCodes returns a slice of strings representing the bits of | ||
// gray codes for the requested number of bits. | ||
func GrayCodes(bits int) []string { | ||
if bits < 1 { | ||
return nil | ||
} else if bits == 1 { | ||
return []string{"0", "1"} | ||
} | ||
smaller := GrayCodes(bits - 1) | ||
result := make([]string, 0, 2*len(smaller)) | ||
for _, entry := range smaller { | ||
result = append(result, fmt.Sprintf("0%s", entry)) | ||
} | ||
for i := range smaller { | ||
result = append(result, fmt.Sprintf("1%s", smaller[len(smaller)-1-i])) | ||
} | ||
return result | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package day148 | ||
|
||
import ( | ||
"reflect" | ||
"testing" | ||
) | ||
|
||
var testcases = []struct { | ||
bits int | ||
codes []string | ||
}{ | ||
{2, []string{"00", "01", "11", "10"}}, | ||
{1, []string{"0", "1"}}, | ||
{0, nil}, | ||
{-10, nil}, | ||
{3, []string{"000", "001", "011", "010", "110", "111", "101", "100"}}, | ||
} | ||
|
||
func TestGrayCodes(t *testing.T) { | ||
t.Parallel() | ||
for _, tc := range testcases { | ||
if result := GrayCodes(tc.bits); !reflect.DeepEqual(result, tc.codes) { | ||
t.Errorf("Expected %v got %v", tc.bits, result) | ||
} | ||
} | ||
} | ||
|
||
func BenchmarkGrayCodes(b *testing.B) { | ||
for i := 0; i < b.N; i++ { | ||
for _, tc := range testcases { | ||
GrayCodes(tc.bits) | ||
} | ||
} | ||
} |