add new solutions
This commit is contained in:
parent
489fa73880
commit
0f5f9e331c
11 changed files with 539 additions and 0 deletions
63
solutions/0/q68/solution.go
Normal file
63
solutions/0/q68/solution.go
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
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
|
||||
Loading…
Add table
Add a link
Reference in a new issue