函数计算一个数组中有多少个值与给定的键互补

Function to count how many values in an array complement with a given key

本文关键字:多少 计算 一个 数组 函数      更新时间:2023-10-16

我尝试了一种算法,该算法将计算矩阵中有多少元素用给定键的最后S个位数来补充其最后S位。

假设s等于3,要验证的数字是12,密钥是3。在二进制表示中,12=(00001100)和3=(00000011)。如果我们将xor应用于这两个值,我们得到15(00001111)。但我们只考虑最后的S(3)位,因为它们都等于1,所以数字是互补的。如果我们有相同的数字12,但密钥是5(00000101),那么xor的结果将返回9(00001001),但最后的S(3)位并不都是1,因此它不是互补的。

我试着在c++中实现这个算法,尽管我一遍又一遍地研究,但我似乎找不到其中的逻辑错误。我问你是因为这个代码用于我处理的一个问题,而自动评估它的网站并没有授予它这个子问题所能获得的所有分数。

int complement()
{
    //map is a globally declared matrix
    //k is the key, also global
    //S is the number of bits we take into account, also global
    int i, j, nr=0, mask, aux;
    mask = (1<<S)-1;
    for(i=1; i<=n; i++)
        for(j=1; j<=m; j++)
        {
            aux = map[i][j]^k;
            if( aux & mask == mask)
            {
                map[i][j]=0;    //overwritten as 0 meaning it is good
                nr++;
            }
            else map[i][j]=-1;  //overwritten as -1
        }
    return nr;     //how many numbers could be complemented
}
For the matrix:
15 1278 3  1278 1278 1 
16 17   18 19   254  20
21 25   26 254  254  254
27 28   29 3    2    254
2  254  4  254  254  254
The program returns:
-1  0 -1  0 0 -1 
 0 -1  0 -1 0  0 
-1 -1  0  0 0  0 
-1  0 -1 -1 0  0 
 0  0  0  0 0  0 
and nr = 20.

限制:

  • S<=8
  • 所有值和键<=9999

C/C++运算符的逐位操作优先级是"错误的"。

在C/C++中

aux & mask == mask

被解析为

aux & (mask == mask)

你需要写

(aux & mask) == mask

因为否则CCD_ 1每次都将以1结束并且与掩模大小无关。