Skip to content

Commit

Permalink
Merge pull request #310 from vaskoz/day148
Browse files Browse the repository at this point in the history
Day148
  • Loading branch information
vaskoz committed Jan 17, 2019
2 parents cabaf72 + afdd4c3 commit fe7553e
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,4 @@ problems from
* [Day 145](https://github.com/vaskoz/dailycodingproblem-go/issues/302)
* [Day 146](https://github.com/vaskoz/dailycodingproblem-go/issues/303)
* [Day 147](https://github.com/vaskoz/dailycodingproblem-go/issues/304)
* [Day 148](https://github.com/vaskoz/dailycodingproblem-go/issues/309)
22 changes: 22 additions & 0 deletions day148/problem.go
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
}
34 changes: 34 additions & 0 deletions day148/problem_test.go
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)
}
}
}

0 comments on commit fe7553e

Please sign in to comment.