ThueMorse.java


Below is the syntax highlighted version of ThueMorse.java from §3.1 Using Data Types.



/*************************************************************************
 *  Compilation:  javac ThueMorse.java
 *  Execution:    java ThueMorse N
 *  Dependencies: StdDraw.java
 *  
 *  Plot the N-by-N Thue-Morse weave. The Thue-Morse sequence is 
 *  defined as follows:
 *  
 *      Start with 0, and repeatedly flip all the bits and concatenate
 *      it onto the original string.
 *
 *  Extend the idea in two dimensions. Plot a black square for 1.
 *
 *  % java ThueMorse 16
 *
 *  % java ThueMorse 128
 *
 *************************************************************************/

public class ThueMorse { 

    public static void main(String[] args) { 
        int N = Integer.parseInt(args[0]);     // plot N-by-N grid of cells

       /******************************************************************
        * build up Thue-Morse sequence
        ******************************************************************/
        String thue   = "0";
        String morse  = "1";
        String t, m;

        for (int i = 1; i < N; i *= 2) {
            t = thue;
            m = morse;
            thue  += m;
            morse += t;
        }

       /******************************************************************
        * Plot it using StdDraw
        ******************************************************************/
        StdDraw.setXscale(0, N);
        StdDraw.setYscale(0, N);
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (thue.charAt(i) != thue.charAt(j)) {
                    StdDraw.filledSquare(i + 0.5, j + 0.5, 0.5);
                }
            }
        }
        StdDraw.show();
    }

}


Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.
Last updated: Wed Feb 9 09:07:43 EST 2011.