63 lines
1.1 KiB
Go
63 lines
1.1 KiB
Go
package q68
|
|
|
|
var (
|
|
emptyLine = make([]byte, 100)
|
|
buf = make([]byte, 100)
|
|
)
|
|
|
|
func init() {
|
|
for i := range emptyLine {
|
|
emptyLine[i] = ' '
|
|
}
|
|
}
|
|
|
|
func emitLine(line []byte, words []string, justifyLeft bool) string {
|
|
spaces := len(line)
|
|
for i := range words {
|
|
spaces -= len(words[i])
|
|
}
|
|
lenSep := spaces / max(len(words)-1, 1)
|
|
leftover := spaces % max(len(words)-1, 1)
|
|
|
|
offset := len(words[0])
|
|
copy(line, words[0])
|
|
for i := 1; i < len(words); i++ {
|
|
var spaces = 1
|
|
if !justifyLeft {
|
|
spaces = lenSep
|
|
if i <= leftover {
|
|
spaces++
|
|
}
|
|
}
|
|
offset += spaces
|
|
copy(line[offset:], words[i])
|
|
offset += len(words[i])
|
|
}
|
|
return string(line)
|
|
}
|
|
|
|
func fullJustify(words []string, maxWidth int) []string {
|
|
ret := []string{}
|
|
line := buf[:maxWidth]
|
|
copy(line, emptyLine)
|
|
|
|
i := 0
|
|
lineLen := len(words[0])
|
|
for j := 1; j < len(words); j++ {
|
|
if lineLen+1+len(words[j]) <= maxWidth {
|
|
lineLen += 1 + len(words[j])
|
|
continue
|
|
}
|
|
|
|
ret = append(ret, emitLine(line, words[i:j], false))
|
|
copy(line, emptyLine)
|
|
|
|
i = j
|
|
lineLen = len(words[j])
|
|
}
|
|
|
|
// Last line
|
|
return append(ret, emitLine(line, words[i:], true))
|
|
}
|
|
|
|
var _ = fullJustify
|