Skip to content

Commit

Permalink
Merge pull request #66 from vaskoz/day28
Browse files Browse the repository at this point in the history
Day28
  • Loading branch information
vaskoz committed Sep 18, 2018
2 parents 1aac333 + 3732468 commit 616d676
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,4 @@ problems from
* [Day 25](https://github.com/vaskoz/dailycodingproblem-go/issues/59)
* [Day 26](https://github.com/vaskoz/dailycodingproblem-go/issues/61)
* [Day 27](https://github.com/vaskoz/dailycodingproblem-go/issues/63)
* [Day 28](https://github.com/vaskoz/dailycodingproblem-go/issues/65)
51 changes: 51 additions & 0 deletions day28/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package day28

import (
"fmt"
"strings"
)

// Justify returns a slice of justified strings.
func Justify(words []string, k int) []string {
var line, result []string
var lineLength int
for i := 0; i < len(words); i++ {
word := words[i]
if lineLength+len(word)+len(line) <= k {
lineLength += len(word)
line = append(line, word)
} else {
result = append(result, buildLine(line, k, lineLength))
line = line[:0] // truncate
lineLength = 0
i-- // retry this word
}
}
last := buildLine(line, k, lineLength)
if last != "" {
result = append(result, last)
}
return result
}

func buildLine(line []string, k, lineLength int) string {
if len(line) == 1 {
spaces := k - lineLength
return fmt.Sprintf("%s%s", line[0], strings.Repeat(" ", spaces))
}
var sb strings.Builder
minimumSpaces := (k - lineLength) / len(line)
extraSpaces := k - lineLength - ((len(line) - 1) * minimumSpaces)
for i, word := range line {
sb.WriteString(word)
if i == len(line)-1 {
break
}
spaces := minimumSpaces
if i < extraSpaces {
spaces++
}
sb.WriteString(strings.Repeat(" ", spaces))
}
return sb.String()
}
35 changes: 35 additions & 0 deletions day28/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package day28

import (
"reflect"
"testing"
)

var testcases = []struct {
words []string
k int
expected []string
}{
{[]string{"bird"},
6,
[]string{"bird "}},
{[]string{"the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"},
16,
[]string{"the quick brown", "fox jumps over", "the lazy dog"}},
}

func TestJustify(t *testing.T) {
for _, tc := range testcases {
if result := Justify(tc.words, tc.k); !reflect.DeepEqual(tc.expected, result) {
t.Errorf("Expected %v but got %v", tc.expected, result)
}
}
}

func BenchmarkJustify(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
Justify(tc.words, tc.k)
}
}
}

0 comments on commit 616d676

Please sign in to comment.