0

I'm trying to print a rectangle of asterisks with its diagonals.

I have the code for it, but I'm wondering if there's any way to make it more symmetrical?

        int height = int.Parse(Console.ReadLine());
        int width = int.Parse(Console.ReadLine());

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (i == 0 || j == 0 || i == height - 1 || j == width - 1 || i == j || i + j == width- 1) {
                    Console.Write("*");
                }
                else {
                    Console.Write(" ");
                }

            }
            Console.WriteLine();
        }

With an imput of (12, 16) it comes out:

****************
**            **
* *          * *
*  *        *  *
*   *      *   *
*    *    *    *
*     *  *     *
*      **      *
*      **      *
*     *  *     *
*    *    *    *
****************
Destiner
  • 540
  • 4
  • 16
helloimkat
  • 23
  • 1
  • 6
  • 1
    Search you are looking for https://www.bing.com/search?q=line+drawing+algorithm. If you can't search - answer with complete code - http://stackoverflow.com/questions/11678693/all-cases-covered-bresenhams-line-algorithm (not exact duplicate as it does not cover drawing 2 lines) – Alexei Levenkov Dec 03 '15 at 00:27
  • _"if there's any way to make it more symmetrical"_ -- what do you think it should look like? The way you're drawing it now, you're limited to 45-degree angles; the only way to draw that symmetrically is to draw them in a square (i.e. width == height). If you want symmetry in non-square rectangles, you'll need to adapt the code to draw other angles. Note that regardless, ASCII art won't have enough resolution for non-rational slopes to ever look exactly right. But you can get closer than the above, if you do some research. – Peter Duniho Dec 03 '15 at 04:34

1 Answers1

1

To draw a diagonal in a height * width rectangle:

    int height = int.Parse(Console.ReadLine());
    int width = int.Parse(Console.ReadLine());

    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            // Calculate the slope
            int x = (int) (0.5 + (1.0 * (i) * width) / (height-0.5));
            if (i == 0 || j == 0 || i == height - 1 || j == width - 1 || x == j || j == width - x - 1) {
                Console.Write("*");
            }
            else {
                Console.Write(" ");
            }

        }
        Console.WriteLine();
    }
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82