Building a right-angled triangle with recursion

I have this homework requiring you to print an asterisk to draw a triangle.

When drawTriangle (0);

 *

When drawTriangle (1);

  *
 **

When drawTriangle (2);

   *
  **
 * *
****

when drawTriangle (3);

       *
      **
     * *
    ****
   *   *
  **  **
 * * * *
********

when drawTriangle (4);

               *
              **
             * *
            ****
           *   *
          **  **
         * * * *
        ********
       *       *
      **      **
     * *     * *
    ****    ****
   *   *   *   *
  **  **  **  **
 * * * * * * * *
****************

when drawTriangle (5);

                               *
                              **
                             * *
                            ****
                           *   *
                          **  **
                         * * * *
                        ********
                       *       *
                      **      **
                     * *     * *
                    ****    ****
                   *   *   *   *
                  **  **  **  **
                 * * * * * * * *
                ****************
               *               *
              **              **
             * *             * *
            ****            ****
           *   *           *   *
          **  **          **  **
         * * * *         * * * *
        ********        ********
       *       *       *       *
      **      **      **      **
     * *     * *     * *     * *
    ****    ****    ****    ****
   *   *   *   *   *   *   *   *
  **  **  **  **  **  **  **  **
 * * * * * * * * * * * * * * * *
********************************

Any advice would be appreciated. Greetings.

+5
source share
6 answers

You noticed that the height of the triangle is 2 ^ n, I'm sure. So you need to print a lot of lines. You also know that you need to remember the previous lines if you are going to copy them somehow, so you know that you need to store them somewhere - perhaps Vector?

, , , . , , , - .

, "*": .

"n" :

  • , "", , .
  • ( , , ):
    • ,
    • , ,

. , , .

(, , , , for . , . , , , [ ] .)

. padRight n, . padLeft, , :

  public static String padRight(String s, int n) {
     return String.format("%1$-" + n + "s", s);
  }

  public static String padLeft(String s, int n) {
    return String.format("%1$#" + n + "s", s);
  }

: , .

+2

OO :

public class Triangle
{
  int n;
  int size;
  char[][] data;

  public Triangle(int n)
  {
    this.n = n;
    this.size = (int)Math.pow(n,2);
    this.data = new char[size][size];
    fillInData();
  }

  void fillInData()
  {
    if (n == 0)
    {
      //stop case
      data[0][0] = '*';
    }
    else
    {
      //create a triangle with n-1
      //fill in the top left quadrant of data[][] with spaces
      //fill in the other 3 quadrants of data[][] with data[][] from the n-1 triangle
    }
  }
}

, , ;

+3

x :

  • , x = 0 ( )
  • Or by placing two x-1 triangles next to each other, and one from the top right one

The complex part includes the print part. The hint here is that the width / height of the level x triangle is 2 ^ x ...

+2
source

Just for fun; here is your problem in Haskell. May not help, but I want to share!

import System

dupl t = zipWith (++) t t

pad n row = (replicate ((2 ^ n) - (length row)) ' ') ++ row

createTriangle 0 = ["*"]
createTriangle n = (map (pad n) prec) ++ (dupl prec)
  where prec = createTriangle $ n - 1

drawTriangle = putStr . unlines . createTriangle

main = getArgs >>= drawTriangle . read . (!! 0)

Run with runhaskell thisstuff.hs [number]

+1
source

Here's a pretty python script ... not many pythons. :(

def triangle(n):
   if n == 0:
      return "*"
   else:
      small = triangle(n-1)
      lines = small.split("\n")
      top = ""
      for line in lines:
         top += len(lines[0])*" " + line + "\n"
      bot = '\n'.join([2*line for line in lines])
      return top + bot


for i in range(5):
   print(triangle(i))

Here is the conclusion

*
 *
**
   *
  **
 * *
****
       *
      **
     * *
    ****
   *   *
  **  **
 * * * *
********
               *
              **
             * *
            ****
           *   *
          **  **
         * * * *
        ********
       *       *
      **      **
     * *     * *
    ****    ****
   *   *   *   *
  **  **  **  **
 * * * * * * * *
****************
+1
source
import java.util.*;

public class Triangle {

    public void drawTriangle(int scale){
     scale = 1 << scale;
     StringBuilder line = new StringBuilder();
     char t = 0;

     for (int i = 0; i <= scale; i++){
           line.append(" ");
     }
     line.setCharAt(scale, '*');

     for(int i = 0; i < scale; i++){
           System.out.println(line);

     for(int j = scale-i; j <= scale; j++){
                 t = line.charAt(j)==line.charAt(j-1) ? ' ':'*';
                 line.setCharAt(j-1,t);
           }

     }

}

    public static void main(String args[]){
        Triangle t = new Triangle();
        t.drawTriangle(5);
    }
}

A few lines of code are enough for this.

0
source

All Articles