-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext-justification.go
77 lines (55 loc) · 1.4 KB
/
text-justification.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
package textjustification
func fullJustify(words []string, maxWidth int) []string {
res := []string{}
n := len(words)
left := 0
for left < n {
l := len(words[left])
right := left + 1
for right < n && (l+len(words[right])+right-left) <= maxWidth {
l += len(words[right])
right++
}
extra := maxWidth - l
if right-left == 1 || right == n {
// left justify
res = append(res, leftJustify(words, left, right, extra))
} else {
// mid justify
res = append(res, midJustify(words, left, right, extra))
}
left = right
}
return res
}
func leftJustify(words []string, left int, right int, extra int) string {
rightSpaces := extra - (right - left - 1)
chars := []byte{}
chars = append(chars, words[left]...)
for i := left + 1; i < right; i++ {
chars = append(chars, (" " + words[i])...)
}
for i := 0; i < rightSpaces; i++ {
chars = append(chars, ' ')
}
return string(chars)
}
func midJustify(words []string, left int, right int, extra int) string {
boundaries := right - left - 1
spaces := extra / boundaries
extraSpaces := extra % boundaries
chars := []byte{}
chars = append(chars, words[left]...)
for i := left + 1; i < right; i++ {
spacesToApply := spaces
if extraSpaces > 0 {
spacesToApply++
extraSpaces--
}
for j := 0; j < spacesToApply; j++ {
chars = append(chars, ' ')
}
chars = append(chars, words[i]...)
}
return string(chars)
}