Hadamard.java


Below is the syntax highlighted version of Hadamard.java from §2.7 Recursion.


/*************************************************************************
 *  Compilation:  javac Hadamard.java
 *  Execution:    java Hadamard n
 *  Dependencies: StdDraw.java
 *  
 *  Plots an order n Hadamard pattern. This is an N-by-N grid of black
 *  and white cells, where N = 2^n. An order 0 Hadamard pattern is 
 *  a black square. An order n Hadamarad pattern is 4 order n-1
 *  Hadamard patterns arranged in a 2-by-2 grid, but the bottom
 *  right is an order n-1 pattern with the roles of black and white
 *  reversed.
 *
 *************************************************************************/

import java.awt.Color;

public class Hadamard { 

    // order n Hadamard pattern with lower left endpoint (x0, y0) and
    // upper right endpoint (x1, y1).
    public static void recur(double x0, double y0, double x1, double y1, int n,
                             double size, boolean color) {
        double x2 = (x0 + x1) / 2.0;
        double y2 = (y0 + y1) / 2.0;

        if (n == 0) {
            if (color) StdDraw.setColor(Color.black);
            else       StdDraw.setColor(Color.white);
            StdDraw.go(x2, y2);
            StdDraw.spot(size, size);
        }
        else {
           recur(x0, y0, x2, y2, n-1, size,  color);   // lower left
           recur(x2, y2, x1, y1, n-1, size,  color);   // upper right
           recur(x0, y2, x2, y1, n-1, size,  color);   // upper left 
           recur(x2, y0, x1, y2, n-1, size, !color);   // lower right
        }

    }

    public static void main(String[] args) { 
        int N = Integer.parseInt(args[0]);

        int SIZE = 512;
        StdDraw.create(SIZE, SIZE);
        StdDraw.clear(Color.black);
        recur(0, 0, SIZE, SIZE, N, SIZE / Math.pow(2, N) - 3, true);
        StdDraw.show();
    }

}


Last updated: Mon Oct 4 13:16:43 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.