Rumpelstiltskin.java


Below is the syntax highlighted version of Rumpelstiltskin.java from §6.1 Data Representations.


/******************************************************************************
 *  Compilation:  javac Rumpelstiltskin.java Converter.java
 *  Execution:    java Rumpelstiltskin N
 *
 *  Enumerate all alphanumeric strings of <= N characters.
 *  Counts from 0 to 36^N - 1 and converts to base 36.
 *  Not the most efficient method, but amazingly little code!
 *
 *  Sample execution:
 *
 *     % java Rumpelstiltskin 4
 *     0
 *     1
 *     ...
 *     ZZZZ
 *
 *
 * Warning: algorithm only works for N <= 5 since 36^6 will overflow
 * an int.  But this prints out 60,466,176 strings. Use a long to go
 * up to N = 12, but be prepared to wait centuries!
 *
 ******************************************************************************/

public class Rumpelstiltskin {

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

        for (int i = 0; i < Math.pow(36, n); i++) {
            StdOut.println(Converter.toString(i, 36));
        }
    }
}


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