-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem028.go
More file actions
51 lines (44 loc) · 1.59 KB
/
Copy pathproblem028.go
File metadata and controls
51 lines (44 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package problem028
import "bytes"
func Justify(words []string, lineLength int) []string {
justifiedWords, lineSizeLeft, wordsInline, spaceCounts := initValues(words, lineLength)
for wordIndex := 0; wordIndex < len(words); {
word := words[wordIndex]
if (len(wordsInline) == 0 && len(word) <= lineSizeLeft) || (len(wordsInline) > 0 && len(word)+1 <= lineSizeLeft) {
if len(wordsInline) > 0 {
spaceCounts = append(spaceCounts, 1)
lineSizeLeft--
}
wordsInline = append(wordsInline, word)
lineSizeLeft -= len(word)
wordIndex++
} else {
justifiedWords = append(justifiedWords, justifyLine(lineSizeLeft, wordsInline, spaceCounts))
_, lineSizeLeft, wordsInline, spaceCounts = initValues(words, lineLength)
}
}
justifiedWords = append(justifiedWords, justifyLine(lineSizeLeft, wordsInline, spaceCounts))
return justifiedWords
}
func justifyLine(lineSizeLeft int, wordsInline []string, spaceCounts []int) string {
if len(wordsInline) == 1 {
spaceCounts = append(spaceCounts, 0)
}
for lineSize := 0; lineSize < lineSizeLeft; lineSize++ {
spaceCounts[lineSize%len(spaceCounts)]++
}
if len(wordsInline) > 1 {
spaceCounts = append(spaceCounts, 0)
}
var buffer bytes.Buffer
for inlineIndex, word := range wordsInline {
buffer.WriteString(word)
for spaceCount := 0; spaceCount < spaceCounts[inlineIndex]; spaceCount++ {
buffer.WriteString(" ")
}
}
return buffer.String()
}
func initValues(words []string, lineLength int) ([]string, int, []string, []int) {
return make([]string, 0, len(words)), lineLength, make([]string, 0, len(words)), make([]int, 0, len(words)/2)
}