GrayCodeArray.java


Below is the syntax highlighted version of GrayCodeArray.java from §2.3 Recursion.


/******************************************************************************
 *  Compilation:  javac GrayCodeArray.java
 *  Execution:    java GrayCodeArray n
 *
 *  Print the n-bit binary reflected Gray code use a pair of mutually
 *  recursive functions and an array.
 *
 *  % java GrayCodeArray 3
 *  000
 *  001
 *  011
 *  010
 *  110
 *  111
 *  101
 *  100
 *
 ******************************************************************************/

public class GrayCodeArray {


    public static void show(boolean[] a) {
        for (int i = 1; i < a.length; i++)
            if (a[i]) StdOut.print(1);
            else      StdOut.print(0);
        StdOut.println();
    }

    public static void yarg(int n, boolean[] a) {
        if (n == 0) show(a);
        else {
            a[n] = true;
            gray(n-1, a);
            a[n] = false;
            yarg(n-1, a);
        }
    }

    public static void gray(int n, boolean[] a) {
        if (n == 0) show(a);
        else {
            a[n] = false;
            gray(n-1, a);
            a[n] = true;
            yarg(n-1, a);
        }
    }


    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        boolean[] a = new boolean[n+1];
        gray(n, a);

    }

}



Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:19:56 EDT 2022.