InversePermutation.java


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


/******************************************************************************
 *  Compilation:  javac InversePermutation.java
 *  Execution:    java InversePermutation 5 0 2 3 1 4
 *
 *  Read in a permutation from the command line and print out the inverse
 *  permutation.
 *
 *    % java InversePermutation 5 0 2 3 1 4
 *    1 4 2 3 5 0
 *
 ******************************************************************************/

public class InversePermutation {
    public static void main(String[] args) {

        int n = args.length;

        // read in permutation
        int[] a = new int[n];
        for (int i = 0; i < n; i++)
            a[i] = Integer.parseInt(args[i]);

        // check if valid
        boolean[] exists = new boolean[n];
        for (int i = 0; i < n; i++) {
            if (a[i] < 0 || a[i] >= n || exists[a[i]])
                throw new RuntimeException("Input is not a permutation.");
            exists[a[i]] = true;
        }

        // invert
        int[] ainv = new int[n];
        for (int i = 0; i < n; i++)
            ainv[a[i]] = i;


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


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