Repository: vaskoz/dailycodingproblem-go (go)

Issue:
Day 148
Good morning! Here's your coding interview problem for today.

This problem was asked by Apple.

Gray code is a binary code where each successive value differ in only one bit, as well as when wrapping around. Gray code is common in hardware so that we don't see temporary spurious values during transitions.

Given a number of bits n, generate a possible gray code for it.

For example, for n = 2, one gray code would be [00, 01, 11, 10].

Pull request description:
Day148
Resolves #309.

Patch:
diff --git a/README.md b/README.md
index 385b836..8228f05 100644
--- a/README.md
+++ b/README.md
@@ -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)
diff --git a/day148/problem.go b/day148/problem.go
new file mode 100644
index 0000000..b54863f
--- /dev/null
+++ b/day148/problem.go
@@ -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
+}


Test patch:
diff --git a/day148/problem_test.go b/day148/problem_test.go
new file mode 100644
index 0000000..853dda7
--- /dev/null
+++ b/day148/problem_test.go
@@ -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)
+		}
+	}
+}