c - 查找二维数组中的交集

标签 c arrays matrix 2d intersection

我写了一个小代码来查找两个二维数组的交集,不幸的是它不起作用,所以也许你可以帮助我..交集是,如果位置(x,y)上的两个数字都是“1”。否则应该是“0”

void intersection(int *mat, int rows, int cols) {    
    int rows1 = 5, cols1 = 4; // secend matrix is in function because i just need it here
    int ma2[] = { 0, 0, 1, 0, 1, // 1. Zeile
                  0, 0, 1, 0, 1, // 2. Zeile
                  0, 0, 1, 1, 0, // 3. Zeile
                  0, 0, 1, 0, 0  // 4. Zeile
                }; 

    int i = 0;
    int j = 0;
    int x = 0;
    int y = 0;

    while (j < cols && y < cols1) { // maybe it is better with a for loop ??
    j += 1;
    y += 1;
    while (i < rows && x < rows1) {
        i += 1;
        x += 1;
        if (mat[j*rows+i] == 1 && ma2[y*rows1+x] == 1) {
            printf("%d ", mat[j*rows+i]);
            break;
            } else {
            printf("%d ", mat[j*rows+i]);
            break;
            }
    }
        printf("\n");
    }
}


int main (void) {
    int rows = 5, cols = 4;  //first matrix is in main, because i need it for other functions
    int ma[] = { 0, 0, 1, 0, 0, // 1. Zeile
                 1, 0, 0, 0, 0, // 2. Zeile
                 1, 0, 1, 0, 0, // 3. Zeile
                 0, 0, 1, 0, 0  // 4. Zeile
                };

    intersection(ma, rows, cols);
    return 0;          
}

输出应该是(在本例中):

           { 0, 0, 1, 0, 0, // 1. Zeile
             0, 0, 0, 0, 0, // 2. Zeile
             0, 0, 1, 0, 0, // 3. Zeile
             0, 0, 1, 0, 0  // 4. Zeile
            };

但我只得到一个 1 行矩阵

问候;)

最佳答案

试试这个

#define min(x,y) ((x) < (y) ? (x) : (y))

void intersection(int *mat, int rows, int cols) {    
    rows = min(rows, 5);//rows <--> cols
    cols = min(cols, 4);
    int ma2[] = { 0, 0, 1, 0, 1, // 1. Zeile
                  0, 0, 1, 0, 1, // 2. Zeile
                  0, 0, 1, 1, 0, // 3. Zeile
                  0, 0, 1, 0, 0  // 4. Zeile
                }; 
    int i, j;

    for(i = 0; i < cols; ++i){
        for(j = 0; j < rows; ++j){
            //printf("%d ", mat[i*rows + j] == ma2[i*rows + j] ? mat[i*rows + j] : 0);
            printf("%d ", mat[i*rows + j] & ma2[i*rows + j]);
        }
        printf("\n");
    }
}

关于c - 查找二维数组中的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26995598/

相关文章:

python - 计算向量python的旋转角度

c - 从设备包含的文件中的 st_dev 字段查找设备文件

arrays - 给定一个整数为 0 到 N 的数组,有多少种排列方式使得 array[i] 不能是 i

c++ - 处理大型数组时超出时间限制

c++ - 如何优化 SIMD 转置函数(8x4 => 4x8)?

c++ 2d数组导致段错误(核心已转储)

c - 默认 gcc 编译器选项是特定于 gcc 版本还是特定于操作系统,还是两者兼而有之?

c - 程序集 x86 从任何文件读取并转义所有特殊字符并获取文件大小(以字节为单位)

java - Java 中的 C/C++ 结构类比?

c - 获取字符串中整数值的数量并将它们存储在数组中