Permutation.java


Below is the syntax highlighted version of Permutation.java from §1.4 Arrays.


/******************************************************************************
 *  Compilation:  javac Permutation.java
 *  Execution:    java Permutation n
 *
 *  Prints a pseudorandom permution of the integers 0 through n-1.
 *
 *    % java Shuffle 6
 *    5 0 2 3 1 4
 *    . * . . . .
 *    . . . . * .
 *    . . * . . .
 *    . . . * . .
 *    . . . . . *
 *    * . . . . .
 *
 ******************************************************************************/

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

        // insert integers 0..n-1
        for (int i = 0; i < n; i++)
            a[i] = i;

        // shuffle
        for (int i = 0; i < n; i++) {
            int r = (int) (Math.random() * (i+1));     // int between 0 and i
            int swap = a[r];
            a[r] = a[i];
            a[i] = swap;
        }

        // print permutation
        for (int i = 0; i < n; i++)
            System.out.print(a[i] + " ");
        System.out.println("");

        // print checkerboard visualization
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (a[j] == i) System.out.print("* ");
                else           System.out.print(". ");
            }
            System.out.println("");
        }
    }
}


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