400.cpp

Back Download
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
// 400.cpp http://acm.uva.es/p/v4/400.html
//
// Solution to ACM problem #400 - "Unix ls"
//
// Matthew Eagar - meagar@gmail.com
// Verified to work as of Sept 15 / 2006
// And again on August 21 / 2007
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
typedef std::vector<std::string> Vec;
typedef Vec::iterator Itr;
int main() {
for (unsigned numFiles; std::cin >> numFiles;) {
std::cin.ignore();
std::cout <<
"------------------------------------------------------------\n";
// Read in names, recording the longest
Vec files(numFiles);
unsigned longest = 0;
for (Itr it = files.begin(); it != files.end(); ++it) {
std::getline(std::cin, *it);
if (it->length() > longest)
longest = it->length();
}
std::sort(files.begin(), files.end());
// find the number of rows and columns in the output
int cols = 0;
while ((++cols + 1) * (longest + 2) - 2 <= 60);
// Calculate the number of rows
int rows = (int)(std::ceil((float)numFiles / (float)cols));
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
// Translate (row,col) to an offset into the files array
unsigned int idx = row + (col * rows);
if (idx < numFiles) {
std::cout << std::setw(longest)
<< std::setiosflags(std::ios::left)
<< files[idx];
// Space between cols
if (col + 1 != cols)
std::cout << " ";
}
}
// end of row
std::cout << std::endl;
}
}
return 0;
}