Skip to main content
2 of 3
Fixed a little grammar
Jamal
  • 34.9k
  • 13
  • 133
  • 237

Attempt at recursive method to draw diamond

I'm not so good with recursion, so I've decided to tackle an exercise consisting of drawing this pattern using characters:

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

Here is my code so far. What could be improved? Furthermore, is recursion suitable for a task like this or not?

class Main
{
    public static void main (String[] args)
    {
        Main.drawDiamond("*", 0, 5 );
    }
    
    public static void drawDiamond( String seed, int turn, int centerLevel ){
        
        if( seed.length() <= 0 ){
            return;
        }
        
        char[] chars = new char[Math.abs(turn-centerLevel-1)];
        Arrays.fill(chars, ' ' );
        String spaces = new String(chars);
        
        System.out.print( spaces );
        
        System.out.println( seed );
        
        if( turn <= centerLevel ){
            seed += "**";
        } else {
            if( seed.length() >= 3 ) {
                 seed = seed.substring(1,seed.length()-1); 
            } else {
                seed = "";
            }
        }

        turn++;
        
        drawDiamond( seed, turn, centerLevel );
    }
}
James P.
  • 413
  • 2
  • 8
  • 14