Saturday, February 14, 2015

Inverse Permutation java in pgm



InversePermutation.java

public class InversePermutation
{
   public static void main(String[] args)
{
   int N = args.length;
      int[] a    = new int[N];
      for (int i = 0; i < N; i++)
         a[i] = Integer.parseInt(args[i]);

      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;
      }

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

No comments:

Post a Comment