...

/

Solution to Sub-task: Split Line

Solution to Sub-task: Split Line

The solution to the Sub-task "Split line" of the project "Justify Text".

We'll cover the following...

Split line

In this step, take an array representation of the line and split it into two sub-array. The first sub-array satisfies the document width constraint.

Press + to interact
function splitLine(line, width){
// Basecases
if (line.length === 0) return [[], []]; // length of line is zero
if (width === 0) return [[], line]; // document width is zero
let [head, ...rest] = line; // destructure line by removing first element
// Recursive case
if(head.length <= width){
// if width greater than first word length
// Reccursively call for remaining line with decreased width
let sub_answer = splitLine(rest, width - (head.length + 1))
// Return by adding the first word into the recursive result
return [[head, ...sub_answer[0]],[...sub_answer[1]]];
}
else{
// Also Basecase
return [[], line];
}
}
console.log(splitLine (["He", "who", "controls"], 15))
console.log(splitLine (["A", "creative", "man"], 10))
console.log(splitLine (["A", "creative", "man"], 11))
console.log(splitLine (["A", "creative", "man"], 12))

The solution takes a recursive approach where the ...