Skip to content

Commit fe7553e

Browse files
authored
Merge pull request #310 from vaskoz/day148
Day148
2 parents cabaf72 + afdd4c3 commit fe7553e

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,3 +158,4 @@ problems from
158158
* [Day 145](https://github.com/vaskoz/dailycodingproblem-go/issues/302)
159159
* [Day 146](https://github.com/vaskoz/dailycodingproblem-go/issues/303)
160160
* [Day 147](https://github.com/vaskoz/dailycodingproblem-go/issues/304)
161+
* [Day 148](https://github.com/vaskoz/dailycodingproblem-go/issues/309)

day148/problem.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package day148
2+
3+
import "fmt"
4+
5+
// GrayCodes returns a slice of strings representing the bits of
6+
// gray codes for the requested number of bits.
7+
func GrayCodes(bits int) []string {
8+
if bits < 1 {
9+
return nil
10+
} else if bits == 1 {
11+
return []string{"0", "1"}
12+
}
13+
smaller := GrayCodes(bits - 1)
14+
result := make([]string, 0, 2*len(smaller))
15+
for _, entry := range smaller {
16+
result = append(result, fmt.Sprintf("0%s", entry))
17+
}
18+
for i := range smaller {
19+
result = append(result, fmt.Sprintf("1%s", smaller[len(smaller)-1-i]))
20+
}
21+
return result
22+
}

day148/problem_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package day148
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
var testcases = []struct {
9+
bits int
10+
codes []string
11+
}{
12+
{2, []string{"00", "01", "11", "10"}},
13+
{1, []string{"0", "1"}},
14+
{0, nil},
15+
{-10, nil},
16+
{3, []string{"000", "001", "011", "010", "110", "111", "101", "100"}},
17+
}
18+
19+
func TestGrayCodes(t *testing.T) {
20+
t.Parallel()
21+
for _, tc := range testcases {
22+
if result := GrayCodes(tc.bits); !reflect.DeepEqual(result, tc.codes) {
23+
t.Errorf("Expected %v got %v", tc.bits, result)
24+
}
25+
}
26+
}
27+
28+
func BenchmarkGrayCodes(b *testing.B) {
29+
for i := 0; i < b.N; i++ {
30+
for _, tc := range testcases {
31+
GrayCodes(tc.bits)
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)