jwaang
jwaang

Reputation: 65

Creating an hourglass using asterisks

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

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

and 3 would look like this:

 ***
  *
 ***

So far I have:

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

and it creates

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

Upvotes: 0

Views: 9340

Answers (2)

ADDruid
ADDruid

Reputation: 196

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
******
 ****
  **
 ****
******

Upvotes: 1

Floris
Floris

Reputation: 46435

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 **

Upvotes: 0

Related Questions