Solution to Sub-task: Line Cost
The solution to the Sub-task "line cost" of the project "Justify Text".
We'll cover the following...
Line cost
Here, use a series of variables and factors to calculate the cost of the line.
Press + to interact
// helper function to find blank positions relative one another// input -> [String] Number eg. ['he', ' ', 'l', 'lo'] 0// Output -> [Number]// eg. [1, 2]/*Each number is the distance of a space character from either the start of theline or the preceding space character. The last number is the distance of theend of line from either the start of the line or the preceding space character.*/function blankPlacements(line, position){if(line.length === 0) return [position];let [head, ...rest] = line;if(head === ' '){return [position, ...blankPlacements(rest, 0)];}else{return blankPlacements(rest, position +1);}}function lineCost(line){// get blank positionslet blankPositions = blankPlacements(line, 0);// get sum of blank positionslet sum = blankPositions.reduce((prev,acc)=> prev + acc ,0);// get average of the positionslet average = sum / blankPositions.length// calculate variance belowlet sumOfSquaredDiff = blankPositions.map(x => (x - average)**2) // squared differences from the mean.reduce((prev,curr) => prev + curr, 0) // sum of differenceslet variance = sumOfSquaredDiff / blankPositions.length;// count hyphenslet hyphenCount = line.map(x => x.match(/[-]/g) ? 1 : 0) // check for hyphens.reduce((prev,acc)=> prev + acc ,0); // count hyphens// count additional blankslet numberOfBlanks = line.map(x => x === ' ' ? 1 : 0) // check for blanks.reduce((prev,acc)=> prev + acc ,0); // count blankslet totalCost = blankCost * numberOfBlanks+ blankProxCost * (line.length - average)+ blankUnevenCost * variance+ hypCost * hyphenCount;return totalCost;}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(lineCost (["He", " ", " ", "who", "cont-"]));console.log(lineCost (["He", " ", "who", " ", "cont-"]));
In this solution, we rely on calculating multiple values using multiple variables for line
. Take into account explicitly introduced placement of space character ' '
in the line line
, for which the solution uses the helper function blankPlacements
(line 23). Use recursion to get these placements in the function with the following properties.