c - 矩阵嵌套在另一个矩阵中

标签 c arrays matrix

我应该使用什么方法来编写一个函数来检查一个矩阵是否包含在另一个矩阵中? 例如:

     matrix A           matrix B
  1   2.  3.  4   5      2  3
  6   7.   8.  9   10    7  8
  11  12. 13. 14  15     12 13
  16  17  18  19  20

我添加了点来指出矩阵 A 内的矩阵 B。

到目前为止我已经写了这个:

#include <stdio.h>

int matrica_sadrzana(int* m1, int v1, int s1, int* m2, int v2, int s2){

    /* What needs to go here? */
    return 0;
}

int main() {
    int i,j,v1,v2,s1,s2,sadrzana;
    int matricaA[100][100],matricaB[100][100];
    printf("Unesite visinu i sirinu matrice A: ");
    scanf("%d %d",&v1,&s1);
    printf("Unesite visinu i sirinu matrice B: ");
    scanf("%d %d",&v2,&s2);
    for(i=0; i<v1; i++){
        for(j=0; j<s1; j++){
            scanf("%d",&matricaA[i][j]);

        }
    }
    for(i=0; i<v2; i++){
        for(j=0; j<s2; j++){
            scanf("%d",&matricaB[i][j]);

        }
    }
    sadrzana=matrica_sadrzana(matricaA,v1,s1,matricaB,v2,s2);

    return 0;
}

最佳答案

您可以创建一个 findNum() 函数,该函数返回 true 或 false 的 bool 值,并接受行大小、列大小、二维数组(由传入的列大小指定的第二维)和一个数字您想检查一下。因此,在您的情况下,您可以遍历矩阵 A,为矩阵 A 中的每个元素调用 findNum() 来检查矩阵 B 是否包含它。 findNum() 将在第一次遇到它要检查的数字时返回 true。如果该数字不存在,则返回 false。

例如:

_Bool findNum(int row, int col, int arr2d[][col], int chk) {
    for(int i = 0; i < row; ++i) {
        for(int j = 0; j < col; ++j) {
            if(arr2d[i][j] == chk)
                return 1;
        }
    }

    return 0;
}

使用它(这应该打印“Match!”三次,因为 0 包含在 arr2d2 但 5 不是):

int arr2d1[2][2] = {0};
int arr2d2[2][3] = {0};

/* Change a value in arr2d1 so they're not identical */
arr2d1[0][0] = 5;

/* Element we're sending to findNum() */
int element = 0;

/* Traverse through arr2d1 */
for(int i = 0; i < 2; ++i) {
    for(int j = 0; j < 2; ++j) {
        element = arr2d1[i][j];
        /* Check if the current element is contained
         * in arr2d2; do whatever if so */
        if(findNum(2, 3, arr2d2, element)) {
            printf("Match!\n");
        }
    }
}

关于c - 矩阵嵌套在另一个矩阵中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53753317/

相关文章:

C - 数字总和

PHP : Remove object from array

c# - 在 C# 中初始化多维数组(与其他数组)

powershell - 交换矩阵中的第一列和最后一列

c++ - 矩阵模板类复制构造函数不起作用?

c - 使用 FFTW 取消定义架构 x86_64 的符号

c - 在 Visual Studio 中测量线程的最大堆栈使用率

将矩阵从 .txt 复制到数组

c - 警告 : assignment makes integer from pointer without a cast ARGV

python - 使用索引数组对多维 numpy 数组进行索引