Creating an hourglass using asterisks

后端 未结 2 1121
情歌与酒
情歌与酒 2021-01-16 16:38

I would like to create an hourglass using the \"*\" character. For example if the user input was 5 then it would look like this:

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


        
相关标签:
2条回答
  • 2021-01-16 17:18

    A complete solution in Java

    public static void draw(int w){
        draw(w, 0);
    }
    
    public static void draw(int W, int s){
        stars(W, s);
        if (W > 2) {
            draw(W-2, s+1);
            stars(W, s);
        }
    }
    public static void stars(int n, int s){
        if(s > 0){
            System.out.print(" ");
            stars(n, s-1);
        } else  if (n > 0){
            System.out.print("*");
            stars(n-1, s);
        } else {
            System.out.println();
        }
    }
    

    the parameter s was introduced to keep track of the number of spaces needed to center the asterisks Another way to do this would be have some global parameter to keep track of the total width and do subtraction but you seem to really like recursion.

    This code

    for(int i = 1; i < 7; i++){
        System.out.println("An hourglass of width " + i);
        draw(i);
        System.out.println();
    }
    

    Will now output this

    An hourglass of width 1
    *
    
    An hourglass of width 2
    **
    
    An hourglass of width 3
    ***
     *
    ***
    
    An hourglass of width 4
    ****
     **
    ****
    
    An hourglass of width 5
    *****
     ***
      *
     ***
    *****
    
    An hourglass of width 6
    ******
     ****
      **
     ****
    ******
    
    0 讨论(0)
  • 2021-01-16 17:22

    Pseudocode:

    function stars(n):
      c1 = 0
      c2 = n
      for i = 1 to n
        print ' ' * c1
        print '*' * c2
        if (i < (n+1) / 2):
          c1 ++;
          c2 -=2;
        else:
          c1--
          c2 +=2
        print newline
    

    This should get you close to your answer... now translate into java

    ** note - this works for odd number. You may need to tweak for even n **

    0 讨论(0)
提交回复
热议问题