Skip to content

Instantly share code, notes, and snippets.

@nsivabalan
Created December 18, 2013 16:52
Show Gist options
  • Select an option

  • Save nsivabalan/8025713 to your computer and use it in GitHub Desktop.

Select an option

Save nsivabalan/8025713 to your computer and use it in GitHub Desktop.
Text Justification
public class TextJustification {
public static void justifyText(String[] words, int width)
{
if(words == null || words.length == 0) return ;
//checkForIllegalArgs(words, width) TO DO
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 +1;
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.println("|");
}
public static void printLeftJustify(String[] words, int width, int start, int end, int totalChars)
{
int spaces = width - totalChars;
int wordCount = start - end +1;
int index = start;
while(index <= end)
{
System.out.print(words[index]+" ");
index++;
}
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