Solution to Sub-task: Blank Insertions
The solution to the Sub-task "blank insertions" of the project "Justify Text".
We'll cover the following...
Blank insertions
In this step, add a certain number of spaces in a line and produce all possible combinations of added spaces at different positions.
Press + to interact
// helper function to permute combinations of adding just one space// input -> [String] eg. ['he', 'l', 'lo']// Output -> [[String]]// eg. [ ['he', ' ', 'l', 'lo'],// ['he', 'l', ' ', 'lo'], ]function singleBlankInsert(line){// when only two words basecaseif(line.length === 2) return [[line[0],' ',line[1]]];// when only one word basecaseif(line.length <= 1) return [line];let [head, ...tail] = line;let answer = singleBlankInsert(tail);answer = answer.map(x => [head, ...x]);answer.push([head, ' ', ...tail]);return answer;}function blankInsertions(num, line){if(num === 0) return [line];if(line.length <= 1) return [line];let answer = blankInsertions(num-1, line);// insert one blank for each line using mapanswer = answer.map(x => singleBlankInsert(x));// flatten the arrayanswer = answer.reduce((prev, curr)=> prev.concat(curr), []);// filter duplicatesreturn Array.from(new Set(answer.map(JSON.stringify)), JSON.parse)}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"],}console.log(blankInsertions( 2, ["A", "creative", "man"]))
Solve this solution recursively, where our base cases are as follows.
- Number of spaces
num
that we need to add is zero (line 19) - Length of the
line
is less than or equal to one, and no spaces are added (line 20