// 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 the
line or the preceding space character. The last number is the distance of the
end 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 positions
let blankPositions = blankPlacements(line, 0);
// get sum of blank positions
let sum = blankPositions.reduce((prev,acc)=> prev + acc ,0);
// get average of the positions
let average = sum / blankPositions.length
// calculate variance below
let sumOfSquaredDiff = blankPositions
.map(x => (x - average)**2) // squared differences from the mean
.reduce((prev,curr) => prev + curr, 0) // sum of differences
let variance = sumOfSquaredDiff / blankPositions.length;
// count hyphens
let hyphenCount = line
.map(x => x.match(/[-]/g) ? 1 : 0) // check for hyphens
.reduce((prev,acc)=> prev + acc ,0); // count hyphens
// count additional blanks
let numberOfBlanks = line
.map(x => x === ' ' ? 1 : 0) // check for blanks
.reduce((prev,acc)=> prev + acc ,0); // count blanks
let 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.0
const blankProxCost = 1.0
const blankUnevenCost = 1.0
const hypCost = 1.0
console.log(lineCost (["He", " ", " ", "who", "cont-"]));
console.log(lineCost (["He", " ", "who", " ", "cont-"]));