Solution to Sub-task: best line break
The solution to the Sub-task "best line break" of the project "Justify Text".
We'll cover the following...
We'll cover the following...
Best line break
In this final step, using functions from previous parts, we break a given line, maximize its length, and return the line with minimum cost using a cost function.
Press + to interact
Node.js
// helper function to find length of the line// input -> [String] eg. ['he', ' ', 'l', 'lo']// Output -> [Number] eg. 6/*There is only one implicit space between two words. There is no implicitspace between a word and an explicit space character or two explicit spacecharacters. The function caters to that length.*/function lineLength(line){if(line.length === 0) return 0;if(line.length === 1) return line[0].length;if(line[0] === ' '){return 1 + lineLength(line.slice(1));}else{return 1 + line[0].length + lineLength(line.slice(1));}}function bestLineBreak(lineCostFunc, dict, width, line){// split into possible lineslet possibleLines = lineBreaks(dict, width, line);// add spacespossibleLines = possibleLines.map(x => {// add blankslet insertedBlanks = blankInsertions(width - lineLength(x[0]), x[0]).map(y => [y, x[1]])return insertedBlanks;}).reduce((prev, curr)=> prev.concat(curr), []); // flatten the array// filter maximum length lines:let maxLength = possibleLines.reduce((max, curr)=>{return max > lineLength(curr[0]) ? max : lineLength(curr[0]);},lineLength(possibleLines[0][0]))// filter all lines of maxLengthpossibleLines = possibleLines.filter(x => lineLength(x[0]) === maxLength);let minimumCostLine = possibleLines.reduce((min, curr)=>{return lineCostFunc(min[0]) > lineCostFunc(curr[0]) ? curr : min;}, possibleLines[0]);return minimumCostLine;}enHyp = {"creative" : ["cr","ea","ti","ve"],"controls" : ["co","nt","ro","ls"],"achieve" : ["ach","ie","ve"],"future" : ["fu","tu","re"],"present" : ["pre","se","nt"],"motivated" : ["mot","iv","at","ed"],"desire" : ["de","si","re"],"others" : ["ot","he","rs"],}const blankCost = 1.0const blankProxCost = 1.0const blankUnevenCost = 1.0const hypCost = 1.0console.log(bestLineBreak (lineCost, enHyp, 15, ["He", "who", "controls"]))
In this solution, take a line
and do the following.
-
Use
lineBreaks
function to split the lineline
and give all possible splits while incorporating broken-hyphenated words viadict
( ...