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]);
        StdOut.println(vonNeumann(n));
    }

}


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