哪个返回矩阵A中不同行的最快方法?(Which is the fastest way to return the number of different rows in a matrix A?)

编程入门 行业动态 更新时间:2024-10-28 10:21:25
哪个返回矩阵A中不同行的最快方法?(Which is the fastest way to return the number of different rows in a matrix A?)

如果我有以下矩阵A:

A = {1,2,3} {7,9,1} {5,3,2}

我如何轻松地返回Matrix中不同的行数? 在这种情况下,输出必须是:“3”

我试图做一个函数“ ”:

void rows (int a[N][N], int row[N], int x){ for (int i=0;i<N;i++){ row[i]=a[x][i]; } }

然后,使用函数“ 检查 ”我试图检查行是否不同:

int check ( int a[N][N]) { int row1[N]; int row2[N]; int j=0; rows(a,row1,j); rows(a,row2,j+1); int count = 0; for ( int i=0; i<N; i++){ for ( int j=0; j<N; j++){ if ( row1[i] != row2[j]){ count++; } } } return count; }

但返回错误的数字,有什么建议?

If i have the following matrix A:

A = {1,2,3} {7,9,1} {5,3,2}

how i can easily return the number of different rows in the Matrix? In this case the output must be : "3"

i tried to make a function "rows":

void rows (int a[N][N], int row[N], int x){ for (int i=0;i<N;i++){ row[i]=a[x][i]; } }

then, with the function "check" i tried to check if the rows are different:

int check ( int a[N][N]) { int row1[N]; int row2[N]; int j=0; rows(a,row1,j); rows(a,row2,j+1); int count = 0; for ( int i=0; i<N; i++){ for ( int j=0; j<N; j++){ if ( row1[i] != row2[j]){ count++; } } } return count; }

but return the wrong number , any suggestions ?

最满意答案

你的算法是完全错误的。 如果增加一个break它在所有行不同时“工作”,但当某些行相同时中断。 它计算行数,使得存在与其不同的另一行。 例如,如果你运行它

1 2 3 4 5 6 1 2 3

你会得到一个答案3 ,但你应该得到一个2 。

算法应该是这样的:

假设所有行都不相同( result = N ) 对于每一行,请看它下面的行 如果行j下面的任何行j与row[i]相等,则减小result并跳出内部循环 在外部循环结束时, result包含您的答案。

Your algorithm is entirely wrong. With an added break it "works" when all rows are different, but it breaks when some of the rows are the same. It counts the number of rows such that there exists another row that's different from it. For example, if you run it on

1 2 3 4 5 6 1 2 3

you will get an answer 3, but you should get a 2.

The algorithm should go like this:

Assume that all rows are distinct (result = N) For each row i, look at the rows below it If any of the rows j below the row i is equal to row[i], decrement the result and break out of the inner loop At the end of the outer loop, result contains your answer.

更多推荐

本文发布于:2023-07-31 06:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1341866.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵   中不   同行   最快   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!