Click here to Skip to main content
15,922,696 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a method from web.
C#
static void Main(String[] args)
{
    var nk = Console.ReadLine().Split(' ').Select(Int32.Parse)
                    .ToArray();
    int n = nk[0];
    int k = nk[1];
    var arr = Console.ReadLine().Split(' ').Select(Int32.Parse)
                     .ToArray();
        
    var count = 0;
    var counts = new int[k];
    for (var i = 0; i < n; i++)
    {
        // the idea is that if (a1 + a2) % k == 0
        // then (a1 % k + a2 % k) should be equal to k (or 0)
        var bucket = arr[i] % k;
        // adding all new combinations with arr[i] to the count
        // also handling bucket == 0 with % k here
        count += counts[(k - bucket) % k];
        counts[bucket]++;
    }
        
    Console.WriteLine(count);
}


The hard part is the last two lines code.
count += counts[(k - bucket) % k];
       counts[bucket]++;

I don't understand it, could you please rewrite it in a better way?

What I have tried:

No clue so far. I tried to step into the code.
Posted
Updated 16-May-18 9:47am

No, not a lot.
count += counts[(k - bucket) % k];
       counts[bucket]++;
The second line is obvious: it's just adding one to an element of an array.
The first row isn't really complicated either, if you break it down:
C#
int index = (k - bucket) % k;
count = count + counts[index];
And I'm sure you know what minus and modulus operators do!
 
Share this answer
 
C#
var bucket = arr[i] % k;
seems to be out of question so I assume "%" and "[]" operators are ok for you.


C#
count += counts[(k - bucket) % k];
The new Thing here is +=. You can write the above also as
C#
count = count + counts[(k - bucket) % k];



C#
counts[bucket]++;
Here I assume "++" is not clear. It means simply increment the value by one. You can write this also this like
C#
counts[bucket]= counts[bucket] + 1;


I hope I could help with this.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900