Word wrap to X lines instead of maximum width (Least raggedness)

后端 未结 8 1774

Does anyone know a good algorithm to word wrap an input string to a specified number of lines rather than a set width. Basically to achieve the minimum width for X lines.

8条回答
  •  猫巷女王i
    2020-12-09 13:46

    btilly has the right answer here, but just for fun I decided to code up a solution in python:

    def wrap_min_width(words, n):
        r, l = [], ""
        for w in words:
            if len(w) + len(l) > n:
                r, l = r + [l], ""
            l += (" " if len(l) > 0 else "") + w
        return r + [l]  
    
    def min_lines(phrase, lines):
        words = phrase.split(" ")
        hi, lo = sum([ len(w) for w in words ]), min([len(w) for w in words])
        while lo < hi:
            mid = lo + (hi-lo)/2
            v = wrap_min_width(words, mid)
            if len(v) > lines:
                lo = mid + 1
            elif len(v) <= lines:
                hi = mid
        return lo, "\n".join(wrap_min_width(words, lo))
    

    Now this still may not be exactly what you want, since if it is possible to wrap the words in fewer than n lines using the same line width, it instead returns the smallest number of lines encoding. (Of course you can always add extra empty lines, but it is a bit silly.) If I run it on your test case, here is what I get:

    Case: "I would like to be wrapped into three lines", 3 lines

    Result: 14 chars/line

    I would like to

    be wrapped into

    three lines

提交回复
热议问题