Last active
August 29, 2015 14:04
-
-
Save ssut/53265df7fb9b1c330717 to your computer and use it in GitHub Desktop.
very weird raggedness word-wrap implementation written in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from sys import argv, exit | |
cac = [] | |
res = [] | |
words = [] | |
M = 0 | |
for x in range(1000): | |
cac.append([-1 for j in range(1000)]) | |
res.append(['' for j in range(1000)]) | |
print 'start' | |
# 0, 45 | |
def go(a, b): | |
if cac[a][b] >= 0: | |
return cac[a][b] | |
if a == b: | |
return 0 | |
csum = -1 | |
i = a | |
while i < b: | |
csum += len(words[i]) + 1 | |
i += 1 | |
if csum <= M or a == (b - 1): | |
i = a | |
while i < b: | |
res[a][b] += words[i] | |
i += 1 | |
cac[a][b] = (M - csum) ** 2 | |
return cac[a][b] | |
ret = 10000000 | |
best_sp = -1 | |
sp = a + 1 | |
while sp < b: | |
cur = go(a, sp) + go(sp, b) | |
if cur <= ret: | |
ret = cur | |
best_sp = sp | |
sp += 1 | |
res[a][b] = '{0}\n{1}'.format(res[a][best_sp], res[best_sp][b]) | |
cac[a][b] = ret | |
return cac[a][b] | |
def main(): | |
global cac, res, words, M | |
M = int(argv[1]) * 2 | |
text = argv[2] | |
for word in text: | |
words.append(word) | |
size = len(words) | |
go(0, size) | |
print res[0][size] | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment