Pretty printing text with even line lengths « Ian Obermiller
The following demo pretty prints the entered text to the desired line width by making the lines as even as possible. The demo uses a dynamic programming algorithm to choose line breaks in such a way that the sum of the squares of the slack is minimized. Line length Basic wrapping Call me Ishmael. Some years ago, never mind how long precisely, having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. Formatted text Javascript Source The javascript source, should work in any ES5 compatible browser: function prettyPrint(text, lineLength) { var words = text.split(' '); var lengths = words.map(function(w) { return w.length; }); var opt = []; var index = []; for (var j = 0; j < words.length; j++) { // Let i be the index that minimizes the expression slack(i, j) + opt[i – 1] var minIndex = -1; var minError = Number.MAX_VALUE; for (var i = 0; i <= j;Read full article from Pretty printing text with even line lengths « Ian Obermiller
No comments:
Post a Comment