Ordinal.java


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


/*************************************************************************
 *  Compilation:  javac Ordinal.java
 *  Execution:    java Ordinal N
 *
 *  Print the von Neumann integer N.
 * 
 *  % java Ordinal 0
 *  {}
 *
 *  % java Ordinal 1
 *  {{}}
 *
 *  % java Ordinal 2
 *  {{}, {{}}}
 *
 *  % java Ordinal 3
 *  {{}, {{}}, {{}, {{}}}}
 *
 *  % java Ordinal 4
 *  {{}, {{}}, {{}, {{}}}, {{}, {{}}, {{}, {{}}}}}
 * 
 * 
 * 
 *  Remarks
 *  -------
 *  Can make more efficient by memoization and avoiding
 *  string concatenation. But this is probably overkill
 *  since the amount of output grows exponentially as
 *  a function of N.
 *
 *************************************************************************/

public class Ordinal {
    public static String vonNeumann(int N) {
        if (N == 0) return "{}"; 
        String s = "";
        for (int i = 0; i < N - 1; i++)
            s += vonNeumann(i) + ", ";
        return "{" + s + vonNeumann(N-1) + "}";
    } 


    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        System.out.println(vonNeumann(N));
    }

}


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