A Character House
National Olympiad — National round (2011 season)
Submission name: house.cpp
Problem summary
Print a centered house. The roof has h rows: row r contains r forward slashes followed by r backslashes. Below it, print a filled rectangle of b rows and 2b equals signs per row. Center the rectangle under the roof.
Input
Two integers h and b.
Output
The house with no blank lines or trailing spaces. The widest roof row starts at column 1.
Constraints
2 < b < h < 40.
Worked example
An independently prepared example for this explanation.
Input
6 3
Output
/\
//\\
///\\\
////\\\\
/////\\\\\
//////\\\\\\
======
======
======
Solution analysis
- The roof’s final width is 2h. Row r has width 2r, so h − r spaces place it in the center.
- The rectangular body has width 2b and height b. Its indentation is (2h − 2b)/2 = h − b spaces. Use repeated-character strings to express each part directly.
- For h = 6 and b = 3, roof indentations are 5, 4, 3, 2, 1, 0. Each body row has three leading spaces and six equals signs, centered beneath the 12-character roof base.
Why it works
Each roof row has exactly r of each slash and the indentation centers its 2r characters within width 2h. Each of the b body rows has width 2b and the same center. No other characters are printed, so the resulting house has exactly the required dimensions and alignment.
Watch out. Escape the backslash in a C++ character literal. Rectangle height is b, width is 2b. Do not add trailing spaces.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
#include <string>
using namespace std;
int main() {
int roofHeight, bodyHeight;
cin >> roofHeight >> bodyHeight;
for (int row = 1; row <= roofHeight; row++) {
// Indent each row so its slash halves share the same center.
cout << string(roofHeight - row, ' ');
cout << string(row, '/');
cout << string(row, '\\') << '\n';
}
for (int row = 0; row < bodyHeight; row++) {
cout << string(roofHeight - bodyHeight, ' ');
cout << string(2 * bodyHeight, '=') << '\n';
}
}