Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.90 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. vector<string> fullJustify(vector<string>& words, int maxWidth) {
  8. vector<string> ret;
  9. int start_word = 0, end_word = 0;
  10. int num_words = end_word - start_word + 1;
  11. int length_of_words = words[0].size();
  12. int space_needed = length_of_words + (num_words - 1);
  13.  
  14. for (int i=0; i<words.size(); ++i) {
  15. int next_word_len = 0;
  16. if (i+1 < words.size())
  17. next_word_len = words[i+1].size();
  18. if (i==words.size()-1 || (num_words==1 && (space_needed+next_word_len+1>maxWidth))) {
  19. //last line or just one word on this line, so left justify
  20. int count_chars = 0;
  21. string line;
  22. for (int j = start_word; j<=end_word; ++j) {
  23. line += words[j];
  24. if (line.size() < maxWidth)
  25. line += ' ';
  26. }
  27. int spaces = maxWidth - line.size();
  28. for (int j=0; j<spaces; ++j)
  29. line += ' ';
  30. ret.push_back(line);
  31. start_word = i+1;
  32. }
  33. else if (num_words>1 && (space_needed+next_word_len+1>maxWidth)) {
  34. //output multi word line, so spread align centre
  35. int words_length = 0;
  36. for (int j=start_word; j<=end_word; ++j)
  37. words_length += words[j].size();
  38. int space_breaks = num_words-1;
  39. int space_chars = maxWidth - words_length;
  40. int chars_per_space = space_chars / space_breaks;
  41. string line;
  42. for (int j=start_word; j<=end_word; ++j) {
  43. line += words[j];
  44. if (j == end_word)
  45. break;
  46. int spaces = chars_per_space;
  47. if (chars_per_space * space_breaks < space_chars)
  48. spaces++;
  49. for (int k=0; k<spaces; ++k)
  50. line += ' ';
  51. space_chars -= spaces;
  52. space_breaks--;
  53. }
  54. ret.push_back(line);
  55. start_word = i+1;
  56. }
  57. //increment counter variables
  58. if (i==words.size()-1)
  59. break;
  60. end_word = i+1;
  61. num_words = end_word - start_word+1;
  62. length_of_words = 0;
  63. for (int j=start_word; j<=end_word; ++j)
  64. length_of_words += words[j].size();
  65. space_needed = length_of_words + (num_words-1);
  66. }
  67. return ret;
  68. }
  69.  
  70. void printv(vector<string>& v) {
  71. for (const string& s : v)
  72. cout << s << "|\n";
  73. cout << "\n";
  74. }
  75.  
  76. int main() {
  77. vector<string> words {"What","must","be","acknowledgment","shall","be"}; //{"Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"}; //{"This", "is", "an", "example", "of", "text", "justification."};
  78. int maxWidth = 16;
  79. auto out = fullJustify(words, maxWidth);
  80. printv(out);
  81.  
  82. return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement