Created
December 18, 2013 17:11
-
-
Save nsivabalan/8026106 to your computer and use it in GitHub Desktop.
Text Justification
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
| public class TextJustification { | |
| public static void justifyText(String[] words, int width) | |
| { | |
| if(words == null || words.length == 0) return ; | |
| //checkForIllegalArgs(words, width) | |
| int start = 0; | |
| int end = 0; | |
| int wordLen = words.length; | |
| int totalChars = 0; | |
| while(end < wordLen) | |
| { | |
| totalChars = 0; | |
| while(end < wordLen) | |
| { | |
| if(totalChars + words[end].length() < width) | |
| totalChars += words[end++].length()+1; | |
| else | |
| break; | |
| } | |
| if(end != wordLen) | |
| { | |
| printJustify(words, width, start, end-1, totalChars); | |
| } | |
| else{ | |
| printLeftJustify(words, width, start, end-1, totalChars); | |
| break; | |
| } | |
| start = end; | |
| } | |
| } | |
| public static void printJustify(String[] words, int width, int start, int end, int totalChars) | |
| { | |
| //System.out.println(" "+start+" "+end+" "+totalChars); | |
| int spaces = width - totalChars; | |
| int wordCount = end - start; | |
| if(wordCount != 0){ | |
| int wordSpace = spaces/wordCount; | |
| int leftOver = spaces%wordCount; | |
| int index = start; | |
| while(index < end) | |
| { | |
| System.out.print(words[index]+" "); | |
| for(int i =0;i<wordSpace;i++) | |
| System.out.print(" "); | |
| if(leftOver > 0){ | |
| System.out.print(" "); | |
| leftOver--; | |
| } | |
| index++; | |
| } | |
| System.out.print(words[index]); | |
| } | |
| else{ | |
| System.out.print(words[start]); | |
| while(totalChars < width){ | |
| System.out.print(" "); | |
| totalChars++; | |
| } | |
| } | |
| System.out.println("|"); | |
| } | |
| public static void printLeftJustify(String[] words, int width, int start, int end, int totalChars) | |
| { | |
| int index = start; | |
| while(index <= end) | |
| { | |
| System.out.print(words[index]+" "); | |
| index++; | |
| } | |
| totalChars++; | |
| while(totalChars < width) | |
| { | |
| System.out.print(" "); | |
| totalChars++; | |
| } | |
| System.out.println("|"); | |
| } | |
| public static void main(String args[]) | |
| { | |
| String[] input = "Geeks forGeeks for text justify problem done".split(" "); | |
| justifyText(input, 15); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment