Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Created July 30, 2022 11:28
Show Gist options
  • Select an option

  • Save anushshukla/05b1fa52a673d03fc3b39af02c648e3a to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/05b1fa52a673d03fc3b39af02c648e3a to your computer and use it in GitHub Desktop.
You are given a list of words. You have a notebook which allows each line to have only ‘W’ numbers of characters.
/*
You are required :
1. pack as many words as you can in each line
2. Extra spaces between words should be distributed as evenly as possible.
3. For the last line of text, it should be left-justified
*/
const getLineOutput = (strArr: string[], maxCharsInLine: number): string[] => {
const lineStrArr = [] as string[];
let line = '';
let lineCharCounter = maxCharsInLine;
let lineComponents = [] as string[];
let lineSpaceComponents = [] as string[];
strArr.forEach(str => {
let charsPendingToAdd = lineCharCounter - str.length - 1;
if (charsPendingToAdd > 0) {
lineComponents.push(str);
lineSpaceComponents.push(' ');
lineCharCounter = charsPendingToAdd;
} else {
lineSpaceComponents.pop();
lineCharCounter += 1;
let lineSpaceComponentsIndex = 0;
// spaces to add 5 and space components are 2
while (charsPendingToAdd) {
if (lineSpaceComponentsIndex === lineSpaceComponents.length) {
lineSpaceComponentsIndex = 0;
}
lineSpaceComponents[lineSpaceComponentsIndex] += ' ';
lineSpaceComponentsIndex++;
charsPendingToAdd--;
}
lineComponents.forEach((lineComponent, index) => {
line += lineComponent;
if (index <= lineSpaceComponents.length) {
line += lineSpaceComponents[index];
}
});
lineStrArr.push(line);
// reset
lineCharCounter = maxCharsInLine;
lineComponents = [];
lineSpaceComponents = [];
line = '';
}
})
return lineStrArr;
}
const testCases = [
{
input: {
arrStr: ["This", "is", "an", "example", "of", "sde2", "interview." , "Bye"],
maxCharsInLine: 16
},
output: [
"This is an",
"example of sde2",
"Interview. Bye "
]
}
]
testCases.forEach(testCase => {
const actualOutput = getLineOutput(testCase.input.arrStr, testCase.input.maxCharsInLine);
console.log('Test case: ', actualOutput.toString() === testCase.output.toString())
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment