Square-root - 5 months ago 26

Java 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];
```