Created
July 30, 2022 11:28
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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