简体   繁体   English

如何检查元素在矩阵(C)中是否存在多次?

[英]How to check if an element exists more than once in matrix (C)?

I'm studying C programming language, and I came across a question that I got stuck trying to solve.我正在学习 C 编程语言,我遇到了一个我一直在试图解决的问题。 I tried searching for an answer to my question, but I couldn't find.我试图寻找我的问题的答案,但我找不到。

My question is how to check if an element exists more than once in a matrix.我的问题是如何检查一个元素是否在矩阵中多次存在。 Also, if it exists more than once but in the same row, it doesn't count.此外,如果它存在多次但在同一行中,则不计算在内。

I tried writing a function to do this, but when I look at it I get a headache hehe, so I guess I did it all wrong from the start.我尝试编写一个函数来执行此操作,但是当我看到它时,我很头疼呵呵,所以我想我从一开始就做错了。

Can someone please tell me how to do it?有人可以告诉我怎么做吗?

Thanks in advance.提前致谢。

  1. Check if an element exists more than once in an matrix: Sort the whole array (as if it would be a single linear vector).检查一个元素是否在矩阵中多次存在:对整个数组进行排序(就像它是一个线性向量一样)。 Then go linear through the vector and check if neighbouring elements are the same.然后线性通过向量并检查相邻元素是否相同。
  2. Check if an element exists more than once in a column of a matrix: Do the same as in 1. but only for each column.检查一个元素在矩阵的一列中是否存在多次:执行与 1. 相同的操作,但仅针对每一列。

For what you ask, you need to analyze all the element in the matrix.对于您的要求,您需要分析矩阵中的所有元素。 You also need to keep track if the element was already found in that column.您还需要跟踪该元素是否已在该列中找到。 Here is a sample code:这是一个示例代码:

int count(int **matrix, int rows, int cols, int number) {
  int count=0, found_in_row=0, i, j;
  for(i=0; i<rows; i++) {
    for(j=0; j<cols; j++) {
      if(matrix[i][j]==number && found_in_row==0) {
        count++;
      }
    }
    found_in_row=0;
  }
 return count;
}

Now suppose i have this matrix:现在假设我有这个矩阵:

1 2 1
1 2 3

By calling count(matrix, 3, 3, 1) you will get 2 as answer.通过调用count(matrix, 3, 3, 1)你会得到 2 作为答案。 That mean that the number 1 occur two times (withount counting the second 1 on the first row).这意味着数字 1 出现了两次(不计算第一行的第二个 1)。 So, by calling count on you matrix you will know if number occur more than once by checking if is greater than 1.因此,通过在矩阵上调用count ,您将通过检查数字是否大于 1 来知道number出现多次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM