using
System;
using
System.Collections.Generic;
using
System.Text;
public
class
TextJustification
{
static
string
JoinALineWithSpace(List<
string
> words,
int
start,
int
end,
int
num_spaces)
{
int
num_words_curr_line = end - start + 1;
StringBuilder line =
new
StringBuilder();
for
(
int
i = start; i < end; i++)
{
line.Append(words[i]);
--num_words_curr_line;
int
num_curr_space = (
int
)Math.Ceiling((
double
)(num_spaces) / num_words_curr_line);
for
(
int
j = 0; j < num_curr_space; j++)
{
line.Append(
' '
);
}
num_spaces -= num_curr_space;
}
line.Append(words[end]);
for
(
int
i = 0; i < num_spaces; i++)
{
line.Append(
' '
);
}
return
line.ToString();
}
static
List<
string
> JustifyText(List<
string
> words,
int
L)
{
int
curr_line_start = 0;
int
num_words_curr_line = 0;
int
curr_line_length = 0;
List<
string
> result =
new
List<
string
>();
for
(
int
i = 0; i < words.Count; i++)
{
++num_words_curr_line;
int
lookahead_line_length = curr_line_length + words[i].Length + (num_words_curr_line - 1);
if
(lookahead_line_length == L)
{
string
ans = JoinALineWithSpace(words, curr_line_start, i, i - curr_line_start);
result.Add(ans);
curr_line_start = i + 1;
num_words_curr_line = 0;
curr_line_length = 0;
}
else
if
(lookahead_line_length > L)
{
string
ans = JoinALineWithSpace(words, curr_line_start, i - 1, L - curr_line_length);
result.Add(ans);
curr_line_start = i;
num_words_curr_line = 1;
curr_line_length = words[i].Length;
}
else
{
curr_line_length += words[i].Length;
}
}
if
(num_words_curr_line > 0)
{
StringBuilder line =
new
StringBuilder(JoinALineWithSpace(words, curr_line_start,
words.Count - 1, num_words_curr_line - 1));
line.Append(
" "
.PadRight(L - curr_line_length - (num_words_curr_line - 1)));
result.Add(line.ToString());
}
return
result;
}
static
List<
string
> splitWords(
string
str)
{
List<
string
> words =
new
List<
string
>();
StringBuilder currentWord =
new
StringBuilder();
foreach
(
char
c
in
str)
{
if
(c !=
' '
)
{
currentWord.Append(c);
}
else
{
words.Add(currentWord.ToString());
currentWord =
new
StringBuilder();
}
}
words.Add(currentWord.ToString());
return
words;
}
static
void
printJustifiedText(List<
string
> result)
{
foreach
(
string
line
in
result)
{
Console.WriteLine(line);
}
}
static
void
justifyTheText(
string
str,
int
L)
{
List<
string
> words;
words = splitWords(str);
List<
string
> result = JustifyText(words, L);
printJustifiedText(result);
}
public
static
void
Main(
string
[] args)
{
string
str =
"GeeksforGeeks is the best computer science portal for geeks."
;
int
L = 16;
justifyTheText(str, L);
}
}