hello guys.
I have created an n × n matrix. I have created a bool to verify that every nonzero element less than n appears only once time in each row and column of the matrix.
For example
1 2 3
3 1 2
0 0 0
1 2 3
2 0 1
3 0 2
1 2 3
3 1 2
2 3 1
this matrixs are ok.
Insted
1 1 2
2 3 1
0 2 3
it is not ok because 1 appear two times in row 1, and
0 0 0
1 2 3
0 2 1
it is not ok because 2 appear two times in column 1.
To do this I have created a counter "nr_times" that is incremented each time that the element will appear on the same column (row). If it is 1, the verify it's OK!. Each time that the rows and the columns are formed by only zero, nr_times is 1. There are no mistakes, but verification does not do what I want.
This is the code:
in fact forCode:#include <iostream> #include <vector> using namespace std; typedef vector< vector<int> > TwoDArray; // bool to verify if it is a latin square bool verifyL(TwoDArray &B){ int n = B[0].size(); int sr[n]; int sc[n]; int nr_times; for(int i = 0; i < n; ++i) { int sum = 0; for(int j = 0; j < n; ++j) sum = sum + B[i][j]; sr[i] = sum; } // check that s appears n times in each row for(int i = 0; i < n; ++i) { if (sr[i] == 0) nr_times = 1; else{ for(int s = 1; s <= n; ++s) { nr_times=0; for(int j = 0; j < n; ++j) if (B[i][j] == s) nr_times++; } } if (nr_times != 1) return false; } for(int j = 0; j < n; ++j) { int sum = 0; for(int i = 0; i < n; ++i) sum = sum + B[i][j]; sc[j] = sum; } // check that s appears n times in each column for(int j = 0; j < n; ++j) { if (sc[j] == 0) nr_times = 1; else{ for(int s = 1; s <= n; ++s) { nr_times = 0; for(int i = 0; i < n; ++i) if (B[i][j] == s) nr_times++; } } if (nr_times != 1) return false; } return true; } // bool to verify if it is a k-latin square int main() { // input order int n; cout << "Enter the order: n="; cin >> n; // 2D array costruction TwoDArray B; B.resize(n); for (int i = 0; i < n; i++) { B[i].resize(n); } for (int i = 0; i < n; i++) for (int j = 0; j < n; j++){ cout << "Enter the entrie in row ["<<i<<"], coloumn ["<<j<<"]"; cin >> B[i][j]; } cout<<"\nYou entered the following square \n"; cout<<"\n"; // print latin square B for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << '|'; cout << B[i][j] << ' '; } cout << "|\n"; } //check if B is a latin square if (verifyL(B)) cout << "This isn't a matrix of order "<<n<<" ok"; else cout << "This is a matrix of order "<<n<<" ok"; return 0; }
0 1
1 2
and
0 0
1 2
verify fail, but it is incorrect
can you help me please?