在二维数组中查找交集

问题描述 投票:-1回答:2

我写了一个小代码来找到两个2d数组的交集,不幸的是它不起作用,所以也许您可以帮我。交集是,如果位置(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行的矩阵

Greets;)

c arrays matrix 2d intersection
2个回答
0
投票

尝试一下

#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");
    }
}

0
投票

我用此解决方案解决了问题;)谢谢大家的帮助...

 void intersection(int *mat, int rows, int cols) {    

    int ma2[4][5] = {{0, 1, 0, 0, 0}, 
                     {0, 1, 0, 0, 0},
                     {1, 1, 0, 1, 0}, 
                     {0, 1, 0, 0, 0}};               

    int i = 0;
    int j = 0;
    int t = 1;
    int s = 0;

    for(j = 0; j < cols; j++) {
        for (i = 0; i < rows; i++) { 
            if (ma2[j][i] && mat[j*rows+i] == 1) {
                printf("%d ", t);
            } else {
                printf("%d ", s);
            }
        }
        printf("\n");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.