Repository: vaskoz/dailycodingproblem-go (go)

Issue:
Day 82
Good morning! Here's your coding interview problem for today.

This problem was asked Microsoft.

Using a read7() method that returns 7 characters from a file, implement readN(n) which reads n characters.

For example, given a file with the content “Hello world”, three read7() returns “Hello w”, “orld” and then “”.

Pull request description:
Day82
Resolves #173.

Patch:
diff --git a/README.md b/README.md
index 9f57cd0..c4d864c 100644
--- a/README.md
+++ b/README.md
@@ -91,3 +91,4 @@ problems from
 * [Day 79](https://github.com/vaskoz/dailycodingproblem-go/issues/167)
 * [Day 80](https://github.com/vaskoz/dailycodingproblem-go/issues/168)
 * [Day 81](https://github.com/vaskoz/dailycodingproblem-go/issues/171)
+* [Day 82](https://github.com/vaskoz/dailycodingproblem-go/issues/173)
diff --git a/day82/problem.go b/day82/problem.go
new file mode 100644
index 0000000..766d167
--- /dev/null
+++ b/day82/problem.go
@@ -0,0 +1,31 @@
+package day82
+
+import (
+	"io"
+)
+
+// Read7 reads only 7 bytes at a time from the given io.Reader.
+func Read7(r io.Reader) string {
+	lr := &io.LimitedReader{R: r, N: 7}
+	b := make([]byte, 7)
+	n, err := lr.Read(b)
+	if err != nil {
+		return ""
+	}
+	return string(b[:n])
+}
+
+// ReadN reads N-bytes using only the Read7 function that reads 7-bytes at a time.
+func ReadN(r io.Reader, N int) string {
+	result := make([]byte, N)
+	readBytes := 0
+	for readBytes < N {
+		b := Read7(r)
+		if len(b) == 0 {
+			break
+		}
+		copy(result[readBytes:], []byte(b))
+		readBytes += len(b)
+	}
+	return string(result[:readBytes])
+}


Test patch:
diff --git a/day82/problem_test.go b/day82/problem_test.go
new file mode 100644
index 0000000..f43d0a7
--- /dev/null
+++ b/day82/problem_test.go
@@ -0,0 +1,42 @@
+package day82
+
+import (
+	"reflect"
+	"strings"
+	"testing"
+)
+
+var testcases = []struct {
+	fileData string
+	n        int
+	reads    int
+	expected []string
+}{
+	{"Hello world", 7, 3, []string{"Hello w", "orld", ""}},
+	{"Hi", 2, 6, []string{"Hi", "", "", "", "", ""}},
+}
+
+func TestReadN(t *testing.T) {
+	t.Parallel()
+	for _, tc := range testcases {
+		r := strings.NewReader(tc.fileData)
+		results := make([]string, 0, tc.reads)
+		for i := 0; i < tc.reads; i++ {
+			results = append(results, ReadN(r, tc.n))
+		}
+		if !reflect.DeepEqual(tc.expected, results) {
+			t.Errorf("Expected %v got %v", tc.expected, results)
+		}
+	}
+}
+
+func BenchmarkReadN(b *testing.B) {
+	for i := 0; i < b.N; i++ {
+		for _, tc := range testcases {
+			r := strings.NewReader(tc.fileData)
+			for i := 0; i < tc.reads; i++ {
+				ReadN(r, tc.n)
+			}
+		}
+	}
+}