#include <vector>
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
vector<string> fullJustify(vector<string> &words, int L) {
if (L == 0 || words.size() == 0) {
return words;
}
size_t start = 0;
size_t wordsCount = 1;
size_t wordsLength = words[0].length();
vector<string> result;
size_t size = words.size();
for (size_t i = 1; i < size; ++i) {
size_t len = words[i].length();
if (wordsLength + wordsCount + len <= L) {
wordsLength += words[i].length();
wordsCount++;
continue;
}
result.push_back("");
string &str = result.back();
float spacesRemain = L - wordsLength;
for (int w = 0; w < wordsCount-1; ++w) {
str += words[start+w];
size_t spacesForWord = ceil(spacesRemain/(wordsCount-w-1));
spacesRemain -= spacesForWord;
str += string(spacesForWord, ' ');
}
str += words[start+wordsCount-1] + string(spacesRemain, ' ');
wordsCount = 1;
wordsLength = len;
start = i;
}
result.push_back("");
string &str = result.back();
float spacesRemain = L - wordsLength;
for (int w = 0; w < wordsCount-1; ++w) {
str += words[start+w];
size_t spacesForWord = 1;
spacesRemain -= spacesForWord;
str += string(spacesForWord, ' ');
}
str += words[start+wordsCount-1] + string(spacesRemain, ' ');
return result;
}
ostream &operator<<(ostream &out, const vector<string> &v) {
for (int i = 0; i < v.size(); ++i) {
cout<< v[i] << endl;
}
cout << endl;
return out;
}
int main(int argc, char const *argv[]) {
vector<string> words;
words.push_back("This");
words.push_back("is");
words.push_back("an");
words.push_back("example");
words.push_back("of");
words.push_back("text");
words.push_back("justification.");
cout << fullJustify(words, 16);
words.clear();
words.push_back("a");
words.push_back("b");
words.push_back("c");
words.push_back("d");
words.push_back("e");
cout << fullJustify(words, 3);
return 0;
}