Question: would someone please explain this example and its answer. I understand if an array has {3,2,6} then its inverse would be {6,2,3}. Is this what being asked because the piece of code below doesn't seem to achieve this?

Suppose that the array int pi[128] contains a permutation of the numbers 0, 1, ...., 127.

What one or two lines of Java code would you use to efficiently produce the inverse of
pi in the array ip[128]?

**ANSWER:** 

```
 for (i=0; i<128; ++i) 
      ip[pi[i]] = i

```

Answer: 
Don't know where you saw that answer, because it is wrong.

To illustrate, let's use array of size 4.  

With `pi = {3,0,1,2}`, result is `ip = {1,2,3,0}`.  

Or `pi = {0,1,2,3}` becomes `ip = {0,1,2,3}`.  

Don't know in what definition of the word "inverse", those would be the right results.

Correct answer is:

```
for (int i = 0; i < 128; ++i)
    ip[i] = pi[127 - i];

```
Following up on @Andreas answer. The answer you have just copies the array. I don't see how that can be called "inversing" the array. I've created a few samples that setup arrays according to the problem (with fewer elements) and print the results.

Example "inverse"'s the array and prints the result
===================================================

```
import java.util.Arrays;

public class HelloWorld{

     public static void main(String []args){
         int arrayLength = 10;
         int[] pi= new int[arrayLength];
         int[] ip = new int[arrayLength];
         int i =0;
         for (i=0; i<arrayLength; ++i) 
              pi[i] = i;

         for (i=0; i<arrayLength; ++i) 
              ip[pi[(arrayLength-1)-i]] = i;
         System.out.println("pi: "+Arrays.toString(pi));
         System.out.println("ip: "+Arrays.toString(ip));
    }
}

```

Result
------

> 
> pi: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
> 
>  ip: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] 
> 
> 
> 

Example based on answer in question
===================================

```
import java.util.Arrays;

public class HelloWorld{

     public static void main(String []args){
         int arrayLength = 10;
         int[] pi= new int[arrayLength];
         int[] ip = new int[arrayLength];
         int i =0;
         for (i=0; i<arrayLength; ++i) 
              pi[i] = i;

         for (i=0; i<arrayLength; ++i) 
              ip[pi[i]] = i;
         System.out.println("pi: "+Arrays.toString(pi));
         System.out.println("ip: "+Arrays.toString(ip));
    }
}

```

Result
------

> 
> pi: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
> 
>  ip: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> 
> 
>