理解两行简单代码 [英] Understand two lines simple code

查看:81
本文介绍了理解两行简单代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自网络的方法。

I have a method from web.

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.

推荐答案

不,不是很多。
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:

int index = (k - bucket) % k;
count = count + counts[index];

我确定你知道运算符和减数运算符的作用!

And I'm sure you know what minus and modulus operators do!


var bucket = arr[i] % k;

似乎没有问题所以我假设%和[] 运营商对你没问题。





seems to be out of question so I assume "%" and "[]" operators are ok for you.


count += counts[(k - bucket) % k];

这里的新东西是 + = 。您也可以将以上内容写成

The new Thing here is +=. You can write the above also as

count = count + counts[(k - bucket) % k];










counts[bucket]++;

这里我假设++不是明确。这意味着只需将值递增1即可。你也可以写这个像

Here I assume "++" is not clear. It means simply increment the value by one. You can write this also this like

counts[bucket]= counts[bucket] + 1;





我希望我可以帮忙解决这个问题。



I hope I could help with this.


这篇关于理解两行简单代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆