Hello , I need help with a certain problem.The task is to check if a nxn matrix has a diagonal,whose numbers are all different.The program should return 1 if it exists such diagonal and 0 if not.Using functions is recommended.I know how to do it only for the main diagonal but I should check every other one and I dont know how.
Example:
5 5 5
5 5 1
5 5 5 should return 1
[ Edit: I misread the problem thinking that it returned 1 when all elements of a diagonal are the same. So much of this post is irrelevant. ]
I know how to do it only for the main diagonal
I'm sorry to say that your program doesn't work for the main diagonal either. With this input, it returns 1 instead of 0:
3 3
1 0 0
1 2 0
1 1 2
One problem is that the while loop in check_diagonals() only executes once. That's because there's a return inside the if at line 8, and a return inside the else at line 10. So regardless of whether the if is true, the function will return.
Let's get check_diagonals working first. Then we can modify the code to check the other diagonal. As kbw said, checking the other diagonal is easy once you know how to check the first one.
Here is pseudo-code for checking the major diagonal. See if you can rewrite check_diagonals to do this:
1 2 3 4 5 6 7
// Check each item on the major diagonal against all items below and to the right of it.
for i=0 to size-1 {
for j = i+1 to size-1 {
if matrix[i][i] != matrix[j][j] then they aren't the same so return 0
}
}
// If you get here then they were all the same. Return 1.
bool check_diagonals(int a[100][100] , int size) {
int result = 1;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size -1; j++) {
if (a[i][i] == a[j][j]) result = 0; break;
}
if (result == 0) break;
}
return result;
}
this one is for the main diagonal , now i have to check every other and the reverse diagonals too
One set of diagonals (parallel to the main diagonal) are the lines i-j=u, constant. Loop through u and either i or j.
The other set of diagonals (orthogonal to the main diagonal) are the lines i+j=v, constant. Loop through v and either i or j.
You can cut it down to 2 nested loops if, on any diagonal, you try and insert into a set<int>, since a set won't permit repeats.
5 5 5
5 5 1
5 5 5
Found distinct diagonal i - j = -1
result = 1
Edit:
You may need to revise your statement of the problem, @gabrinka. It occurs to me that if you allow ALL the diagonals of the matrix then the diagonals that just include corner elements (and hence have only one element) automatically and trivially satisfy your criterion. Are you sure that you don't want just the main diagonal and the full diagonal at right angles to it?