Advertisement
incinirate

Typeset

Jul 9th, 2016
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.46 KB | None | 0 0
  1. local args = {...}
  2. if #args < 2 then
  3.   printError("Usage: typset <file> <marginsize>")
  4.   return
  5. end
  6.  
  7. local function split(str, regex)
  8.   local t = {}
  9.   for n in str:gmatch("[^"..regex.."]+") do
  10.     t[#t + 1] = n
  11.   end
  12.   return t
  13. end
  14.  
  15. local handle = fs.open(args[1],"r")
  16. local line = handle.readLine()
  17. local words = split(line, "%s")
  18. local n = #words
  19. local M = tonumber(args[2])
  20. local lens = {}
  21. for i=1, n do
  22.   lens[i] = #words[i]
  23.   if lens[i] > M then
  24.     printError("Lzy c0de, 2 big")
  25.     return
  26.   end
  27. end
  28.  
  29. --compute S_ij
  30. local S = {}
  31. for i = 1, n do
  32.   S[i] = {}
  33.   S[i][i] = M - lens[i]
  34.   for j = i + 1, n do
  35.     S[i][j] = S[i][j - 1] - lens[j] - 1
  36.     if S[i][j] < 0 then
  37.       while j <= n do
  38.         j = j + 1
  39.         S[i][j] = math.huge
  40.       end
  41.     end
  42.   end
  43. end
  44.  
  45. --compute best_0,...,best_n
  46. local best = {}
  47. local choice = {}
  48. best[0] = 0
  49. choice[0] = 0
  50. for i=1, n do
  51.   local min = math.huge
  52.   local ch = 0
  53.   for j=0, i - 1 do
  54.     local t = best[j] + S[j + 1][i] * S[j + 1][i]
  55.     if t < min then
  56.       min = t
  57.       ch = j
  58.     end
  59.   end
  60.   best[i] = min
  61.   choice[i] = ch
  62. end
  63.  
  64. --backtrack to output linebreaks
  65. local endc = n
  66. local start = choice[endc]+1
  67. local lines = {}
  68. while endc > 0 do
  69.   local buff = {}
  70.   for j=start, endc do
  71.     buff[#buff + 1] = words[j]
  72.   end
  73.   lines[#lines + 1] = table.concat(buff, " ").."\n"
  74.   endc = start - 1
  75.   start = choice[endc] + 1
  76. end
  77.  
  78. for j=#lines, 1, -1 do
  79.   write(lines[j])
  80. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement