Repository: vaskoz/dailycodingproblem-go (go)

Issue:
Day 57
Good morning! Here's your coding interview problem for today.

This problem was asked by Amazon.

Given a string s and an integer k, break up the string into multiple texts such that each text has a length of k or less. You must break it up so that words don't break across lines. If there's no way to break the text up, then return null.

You can assume that there are no spaces at the ends of the string and that there is exactly one space between each word.

For example, given the string "the quick brown fox jumps over the lazy dog" and k = 10, you should return: ["the quick", "brown fox", "jumps over", "the lazy", "dog"]. No string in the list has a length of more than 10.

Pull request:
Day57
Resolves #124.

Patch:
diff --git a/README.md b/README.md
index d605c51..5787fc2 100644
--- a/README.md
+++ b/README.md
@@ -68,3 +68,4 @@ problems from
 * [Day 54](https://github.com/vaskoz/dailycodingproblem-go/issues/118)
 * [Day 55](https://github.com/vaskoz/dailycodingproblem-go/issues/121)
 * [Day 56](https://github.com/vaskoz/dailycodingproblem-go/issues/123)
+* [Day 57](https://github.com/vaskoz/dailycodingproblem-go/issues/124)
diff --git a/day57/problem.go b/day57/problem.go
new file mode 100644
index 0000000..3e8d9a5
--- /dev/null
+++ b/day57/problem.go
@@ -0,0 +1,32 @@
+package day57
+
+import "strings"
+
+// BreakByLength takes a long string and then breaks it into full-word
+// strings that are no longer than k characters.
+func BreakByLength(long string, k int) []string {
+	var result []string
+	words := strings.Split(long, " ")
+	var line []string
+	ll := 0
+	for i := 0; i < len(words); i++ {
+		if ll == 0 && len(words[i]) <= k {
+			line = append(line, words[i])
+			ll = len(words[i])
+		} else if ll+len(words[i])+1 <= k {
+			line = append(line, words[i])
+			ll += len(words[i]) + 1
+		} else if ll > 0 {
+			result = append(result, strings.Join(line, " "))
+			line = line[:0]
+			ll = 0
+			i--
+		} else {
+			return nil
+		}
+	}
+	if ll > 0 {
+		result = append(result, strings.Join(line, " "))
+	}
+	return result
+}


Test patch:
diff --git a/day57/problem_test.go b/day57/problem_test.go
new file mode 100644
index 0000000..cb2e892
--- /dev/null
+++ b/day57/problem_test.go
@@ -0,0 +1,30 @@
+package day57
+
+import (
+	"reflect"
+	"testing"
+)
+
+var testcases = []struct {
+	long     string
+	k        int
+	expected []string
+}{
+	{"the quick brown fox jumps over the lazy dog",
+		10,
+		[]string{"the quick", "brown fox", "jumps over", "the lazy", "dog"},
+	},
+	{"the quick brown fox jumps over the lazy dog",
+		4,
+		nil,
+	},
+}
+
+func TestBreakByLength(t *testing.T) {
+	t.Parallel()
+	for _, tc := range testcases {
+		if result := BreakByLength(tc.long, tc.k); !reflect.DeepEqual(tc.expected, result) {
+			t.Errorf("Expected %v got %v", tc.expected, result)
+		}
+	}
+}