Saturday, October 11, 2014

#codingexercise
Text justification
This problem requires the text in sentences to be broken and laid out in a way where each line has L characters except for maybe the last line. Words that break on a line move on to the next and padding introduced evenly between the remaining words.
Let X and Y denote sentences with count of characters less than or equal to L and more than L respectively
The test cases are
X
Y
XX
XY
YX
YY

List<string> Justify(string text, int L)
{
 if (string.IsNullOrEmpty(text) || L < 1) return null;

var ret = new List<string>();
string candidate = string.Empty;

var words = text.split();
 for (int I = 0; I < words.Count; I++)
 {
   // add word  
   if (candidate.Length + words[I].Length  +  1 <= L)
   {
     candidate += words[I] + " ";
     continue;
    }

   // add padding
   if (candidate.Length > 0)
   {
   int padLen = L - candidate.Length;
   if (padLen > 0)
   {
   var w = candidate.Split();
   candidate = string.Empty;
   for (int k = 0; k < w.Count; k++)
   {
       candidate += w[k] + " ";
       for (int l = 0; l <  padLen / w.Count && candidate.Length < L; l++)
          candidate += " ";    
   }

   if (w.Count > 0 && padLen > 0)
   for (int l = 0; l < padLen % w.Count && candidate.Length < L; l++)
         candidate += " ";
   ret.Add(candidate);
   candidate = string.Empty;
   }

    if (candidate.Length + words[I].Length  +  1 <= L)
   {
     candidate += words[I] + " ";
    }
   else
   {
     candidate += words[I].substring(0,L-1) + "-";
     ret.Add(candidate);
     candidate += words[I].substring(L) + " ";
   }

 }
ret.Add(candidate);
return ret;
}
 

No comments:

Post a Comment