This is a nice problem if you want an elegant solution. Here is my second attempt (the first was the most obvious solution using counters and all kind of mess):
Code:
#include <iostream>
#include <string>
void ch_fill ( char ch, int n )
{
for ( int i = 0; i < n; ++i )
std::cout<< ch;
std::cout<<'\n';
}
void hourglass ( std::string word )
{
// Handle a single character string
int len = word.length();
if ( len == 1 ) {
ch_fill ( word[0], 1 );
return;
}
// Deal with even and odd length strings
int mid, mod;
if ( len % 2 == 0 ) {
mid = word.length() / 2;
mod = 1;
}
else {
mid = word.length() / 2 + 1;
mod = 2;
}
// Perform the magic
int i;
for ( i = 0; i < mid; ++i )
ch_fill ( word[i], mid - i );
for ( i = mid; i < len; ++i )
ch_fill ( word[i % len], i % mid + mod );
}
int main()
{
std::string word;
std::cout<<"Enter a word: ";
std::getline ( std::cin, word );
hourglass ( word );
return 0;
}
That was fun, do you have any other problems?
-Prelude