-6
for (int i = 0; i< n; i++)
    arr[arr[i]%k] += k;

I'm new to programming and I came across this piece of code here. Can anyone explain what it does?

Niall
  • 30,036
  • 10
  • 99
  • 142
PapluTaplu
  • 15
  • 1
  • 1
    You may refer to http://stackoverflow.com/questions/5739024/finding-duplicates-in-on-time-and-o1-space – ACcreator Sep 23 '14 at 06:46
  • Read a good C programming book (and C++ is not C). Compile with all warnings and debug info (`gcc -Wall -g`). Run the code step by step in a debugger (`gdb`) – Basile Starynkevitch Sep 23 '14 at 06:47
  • I understand that it is adding k to the value. It's the arr[arr[i]] part that i find confusing. – PapluTaplu Sep 23 '14 at 06:48
  • 1
    @PapluTaplu: Just break it down into simple expressions. It's reading an array element (at index `i`), performing a calculation on it (reducing it modulo `k`), using the result as another array index, and adding `k` to the element at that index. – Mike Seymour Sep 23 '14 at 06:51
  • The page you linked to seems to have a pretty thorough explanation of what the code does. What exactly are you confused about? – MooseBoys Sep 23 '14 at 06:59
  • Also worth mentioning that adding k to elements you encounter doesn't change the indices they point to, so essentially this code goes over the array in a recurring manner using the indices stored, and counts (in multiplication of k) how many times you visit each entry within n steps. – Leeor Sep 23 '14 at 07:08

3 Answers3

0

Translate to:

for (int i = 0; i< n; i++) {
    int temp1 = arr[i];
    int temp2 = temp1%k;
    int temp3 = arr[temp2];
    arr[temp2] = temp3+k;
}

Edit: thanks for the correction @R Sahu

in need of help
  • 1,606
  • 14
  • 27
0

The loop

for (int i = 0; i< n; i++)
    arr[arr[i]%k] += k;

is equivalent to

for (int i = 0; i< n; i++)
{
   int temp1 = arr[i];
   int temp2 = temp1%k;
   arr[temp2] = arr[temp2]+k;    
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0
arr[arr[i]%k] += k;

arr // (array)
arr[i]; // hereinafter "x"  (The i-th element of the array)
x%k; // hereinafter "res" (result of the modulo)
arr[res]; //(The res-th element of the array)
wsc
  • 50
  • 1
  • 8