There's many ways to print a diamond. Consider a diamond with a "radius" of 2:
Code:
* radius of 2
***
*****
***
*
The next step I took to create an algorithm was to note the coordinates of each spot where a * was printed:
Code:
0,2 radius of 2
1,1 1,2 1,3
2,0 2,1 2,2 2,3 2,4
3,1 3,2 3,3
4,2
I really don't know how to describe the next step. It seemed to me that taking the absolute value of the difference of both the row and the radius and the column and the radius might help. So, I wrote those down:
Code:
2,0
1,1 1,0 1,1
0,2 0,1 0,0 0,1 0,2
1,1 1,0 1,1
2,0
I then noticed a pattern. The sum of those differences were never greater than the radius. I checked the points outside my diamond to make sure I was on the right track:
Code:
4 3 2 3 4
3 2 1 2 3
2 1 0 1 2
3 2 1 2 3
4 3 2 3 4
Then I coded it up and tested it for a few other cases. Looks like it works to me.
Code:
static void PrintDiamond(int radius)
{
Debug.Assert(radius >= 0);
int diameter = radius * 2 + 1;
for (int line = 0; line < diameter; line++)
{
for (int col = 0; col < diameter; col++)
{
if (Math.Abs(col - radius) + Math.Abs(line - radius) <= radius)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
I can't really explain how to come up with an algorithm like that. It's just about finding the patterns.