A Diamond of Digits
National Olympiad — Regional round (2010 season)
Submission name: rhomb.cpp
Problem summary
Print a diamond of 2N − 1 rows. A row of size k begins with N − k spaces and contains digits k down to 1 and then 2 up to k. Row sizes rise from 1 to N and then fall back to 1.
Input
An integer N.
Output
The diamond, with no spaces between digits and no blank lines before it.
Constraints
2 ≤ N ≤ 9.
Worked example
An independently prepared example for this explanation.
Input
3
Output
1 212 32123 212 1
Solution analysis
- For row index r from 1 through 2N − 1, choose size k = min(r, 2N − r). This produces the increasing and decreasing halves without duplicating the middle row.
- Print N − k leading spaces, then the descending digits k … 1 and ascending digits 2 … k. Starting the second loop at 2 keeps the central 1 unique.
- For N = 3 the sizes are 1, 2, 3, 2, 1. The middle row has no leading spaces and reads 32123.
Why it works
The size formula gives exactly the required sequence of row sizes. Each row has the prescribed indentation and symmetric digits centered on one 1. Therefore all rows form the specified diamond.
Watch out. Do not repeat the central 1 or the widest row. Leading spaces matter; trailing spaces are unnecessary.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
for (int row = 1; row < 2 * n; row++) {
// Rise to the widest row once, then mirror the row sizes.
int size = min(row, 2 * n - row);
cout << string(n - size, ' ');
for (int digit = size; digit >= 1; digit--) {
cout << digit;
}
for (int digit = 2; digit <= size; digit++) {
cout << digit;
}
cout << '\n';
}
}