如果我有以下矩阵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 3you 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.更多推荐
发布评论