Reputation: 1402
I want to draw a hollow rectangle with it's diagonals. The height of rectangle should be greater than 5 and at most 20. The witdh should be also greater than 5 and at most 80. I already got this code:
using System;
public class Test
{
public static void Main()
{
Console.Write("Enter width of rectangle: ");
int w = int.Parse(Console.ReadLine());
Console.Write("Enter height of rectangle: ");
int h = int.Parse(Console.ReadLine());
Console.WriteLine();
if(w > 5 && w <= 80 && h > 5 && h <= 20)
{
draw(w, h);
}
else
{
Console.WriteLine("Invalid entry!");
}
}
static void draw(int w, int h)
{
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
if ((i == 0) || (j == 0) || (i == h - 1) || (j == w - 1) || (i == j) || (i + j == w - 1) )
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
} Console.WriteLine();
}
}
}
But this code draws correctly only for squares. For rectangles it doesn't draw diagonals correctly. Any help would be greatly appreciated.
Upvotes: 0
Views: 1067
Reputation: 5904
When the rectangle is not a square you have to take in account the ratio between the width and the height. You could do it like this:
using System;
public class Test
{
static int width;
static int height;
public static void Main()
{
Console.Write("Enter width of rectangle: ");
width = int.Parse(Console.ReadLine());
Console.Write("Enter height of rectangle: ");
height = int.Parse(Console.ReadLine());
Console.WriteLine();
if(width > 5 && width <= 80 && height > 5 && height <= 20)
{
draw();
}
else
{
Console.WriteLine("Invalid entry!");
}
}
static void draw()
{
Console.WriteLine((float)width/(float)height);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (IsBorder(x, y) || IsDiagonal(x, y))
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
} Console.WriteLine();
}
}
static bool IsBorder(int x, int y)
{
return x == 0
|| y == 0
|| x == width - 1
|| y == height - 1;
}
static bool IsDiagonal(int x, int y)
{
return width < height
? IsDiagonalHigh(x, y)
: IsDiagonalWide(x,y);
}
static bool IsDiagonalHigh(int x, int y)
{
var aspectRatio = (float)width / (float)height;
return x == (int)(y * aspectRatio)
|| x == width - (int)(y * aspectRatio) - 1;
}
static bool IsDiagonalWide(int x, int y)
{
var aspectRatio = (float)height / (float)width;
return y == (int)(x * aspectRatio)
|| y == (int)((width - x - 1) * aspectRatio);
}
}
As you can see I took the liberty to change w
and h
to the static fields width
and height
.
Upvotes: 1