-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathAyush1
More file actions
73 lines (57 loc) · 2.01 KB
/
Ayush1
File metadata and controls
73 lines (57 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//This code prompts the user to enter the number of words, the words themselves, and the maximum width. It then prints the justified text based on the user input.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> result;
int i = 0;
while (i < words.size()) {
int j = i + 1, currentLen = words[i].size();
// Add words to the current line until maxWidth is reached
while (j < words.size() && currentLen + words[j].size() + (j - i - 1) < maxWidth) {
currentLen += words[j].size();
j++;
}
int spaces = maxWidth - currentLen;
// Distribute spaces between words
int extraSpaces = j - i - 1;
string line = words[i];
// If it's the last line or only one word in the line
if (j == words.size() || extraSpaces == 0) {
for (int k = i + 1; k < j; k++) {
line += ' ' + words[k];
}
line += string(maxWidth - line.size(), ' '); // Pad extra spaces for the last line
} else {
int spacesBetweenWords = spaces / extraSpaces;
int extraSpacesRemaining = spaces % extraSpaces;
for (int k = i + 1; k < j; k++) {
int spacesToAdd = spacesBetweenWords + (extraSpacesRemaining-- > 0 ? 1 : 0);
line += string(spacesToAdd, ' ') + words[k];
}
}
result.push_back(line);
i = j;
}
return result;
}
int main() {
int n;
cout << "Enter the number of words: ";
cin >> n;
vector<string> words(n);
cout << "Enter the words: ";
for (int i = 0; i < n; i++) {
cin >> words[i];
}
int maxWidth;
cout << "Enter the maximum width: ";
cin >> maxWidth;
vector<string> result = fullJustify(words, maxWidth);
cout << "Justified Text:" << endl;
for (const string& line : result) {
cout << line << endl;
}
return 0;
}