-1

I tried to solve the next problem from geeksforgeek website. Given an array of size n where all elements are in range from 0 to n-1, change contents of arr[] so that arr[i] = j is changed to arr[j] = i. I saw a solution using modulo:

during one scan arr[arr[i]%n] += n*i and in the next scan arr[i]/=n

his explanation:

What i did here was this, I knew that every location will have an element less than n since it has to represent an index of the array, For any number x, such that x is less than n, x%n = x basically when i write, arr[arr[i]%n] and if arr[i]=j i'm accessing the element at arr[j] now you'll notice , i'm incrementing each such element with n*i at this step, i'm storing two elements in one location, For eg: suppose arr[2]=5 and arr[5]=4 and there are 6 elements in total i'll make arr[arr[2]%6]=arr[5%6]=arr[5]= 4+12 i.e. 4 + 2*6 which is equal to 16 now this contains both the numbers, if i wan't the original number, i.e. during the first scan when i'm changing all the values, i write arr[5]%6 = (4 + 2*6)%6 = 4%6 + 2*6%6 = 4 + 0 = 4 and during the second scan, when i want to update the array to the final resultant arr[5]/6 = (4 +2*6)/6 = 4/6 + 2*6/6 = 0 + 2 = 2 I hope this explanation helps you, all the best

But I can't understand the logic/math behind it. can someone explain in a mathematical way the logic of the method?

kicklog
  • 109
  • 2
  • 8
  • I actually didn't get the same answer at all. arr = [1 4 5 0 2 3]; n = 6; i = 4; arr[arr[4]%6] += 6 * 4; arr[2] += 24; arr[2] = 29; arr[4] = 2 / 6; arr[4] = 0; – InfinityCounter Jul 17 '17 at 00:47
  • @InfinityCounter You should continue on arr[2]. arr[2] = 29 -> (2nd scan) arr[2] = 29 / 6 => arr[2] = 4 – hk6279 Jul 17 '17 at 03:01
  • can't understand why no one can give me an answer. I tried to edit my question, maybe now it's more clear. – kicklog Jul 17 '17 at 06:43

1 Answers1

1

The trick here is to store two numbers in the range 0..n-1 in one array element. Say if you want to store x and y you actually set the element to z=n*x+y. You can retrieve x by doing z/n and y by doing z%n.

The solution now puts the new numbers into the array (in the x slot) without disturbing the old ones (still in the y slot) using the above trick. In the second pass, the old numbers are removed.

Henry
  • 42,982
  • 7
  • 68
  • 84