Skip to content

Making a Fractal in Java’s Console

From, Data Structures and Other Objects Using Java, Chapter 8, Project #9, page 440:

Examine this pattern of asterisks and blanks and write a recursive method that can generate exactly this pattern:

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

With recursive thinking, the method needs only seven or eight lines of ode (including two recursive calls). How is this pattern a fractal? Your method should also be capable of producing larger or smaller patterns of the same variety. Hint: Have two parameters. One parameter indicates the indentation of the leftmost line in the pattern; the other parameter indicates the number of stars in the longest line.

WARNING: Cheating is bad, mmmmkay children? Don’t cheat.


 /*
|	Bryan Simonson
 \	CS211 - Craig Niiyama
  | 2/21/2010
*/

package bryansimonson;

public class Fractal {
	public static void main(String args[]){
		drawFractal(32,0);
	}

	public static void drawFractal(int length, int space){
		if (length==1){ // the stopping case
			for (int n=0; n<space; n++) System.out.print("  ");
			System.out.println("* ");
		} else {		// length is a power of two
			drawFractal(length/2,space);
			for (int n=0; n<space; n++) System.out.print("  ");
			for (int n=0; n<length; n++) System.out.print("* ");
			System.out.println();
			drawFractal(length/2,length/2+space);
		}
	}
}

One Comment

  1. Hey, I never understand your stuff, but I love that you post it!

    Saturday, April 10, 2010 at 8:21 pm | Permalink

Post a Comment

You must be logged in to post a comment.