-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
85 lines (71 loc) · 1.63 KB
/
main.go
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(fullJustify([]string{"What", "must", "be", "acknowledgment", "shall", "be"}, 16))
}
func fullJustify(words []string, maxWidth int) []string {
var count int
var tmp, result []string
for i, v := range words {
count += len(v)
tmp = append(tmp, v)
if i != len(words)-1 {
if count+len(words[i+1])+len(tmp)-1 >= maxWidth {
result = append(result, getText(tmp, count, maxWidth))
count = 0
tmp = nil
}
}
}
if len(tmp) == 1 {
result = append(result, getText(tmp, count, maxWidth))
} else {
result = append(result, getLastText(tmp, maxWidth))
}
return result
}
func getLastText(str []string, mw int) string {
result := strings.Builder{}
var count int
for i, v := range str {
count += len(v)
result.WriteString(v)
if i != len(str)-1 {
result.WriteRune(' ')
count++
}
}
return result.String() + strings.Repeat(" ", mw-count)
}
func getText(str []string, currSize, mw int) string {
emptySpace := mw - currSize
var (
countSpaces = emptySpace
countModSpaces int
)
if len(str) != 1 {
countSpaces = emptySpace / (len(str) - 1)
countModSpaces = emptySpace % (len(str) - 1)
}
result := strings.Builder{}
for pos, v := range str {
if v == "-1" {
continue
}
result.WriteString(v)
for i := 0; i < countSpaces; i++ {
if pos != len(str)-1 || len(str) == 1 {
result.WriteRune(' ')
}
}
if countModSpaces != 0 {
countModSpaces--
result.WriteRune(' ')
}
}
// fmt.Printf("empty=%v, spaces=%v, modSpaces=%v, len(str)=%v\n", emptySpace, countSpaces, countModSpaces, len(str))
return result.String()
}