I have a question about reflexive arrays, I want to clarify one thing for those who want to edit this question: this question is from a COMPILED code AND WORKS WELL, it is just a question regarding the programming style.
This is the statement of the exercise:
Implement the method bool matrix_t::is_reflexive(void), which returns true if the
relation described in the matrix is reflective, or false otherwise. That is, it returns true if every element of A. is related to itself.
Attention, this is the code of the solved exercise:
bool is_reflexive(void)
{ bool is_ref = true;
int i = 1;
while ((is_ref == true) && (i <= get_m())) {
if (get(i,i) != 1)
is_ref = false;
i++;
}
return is_ref;
}
THE WAY I DID IT:
bool matrix_t<int>::is_reflexive(void){
for (int i=1; i<m_ && !encontrado;i++){
for(int j=1;j<n_ && !encontrado;j++){
if(get(i,i) !=0){
encontrado = true;
}
}
}
return encontrado;
}
My question is: looping through rows and columns instead of rows only makes my code inefficient? initialize found to false makes it inefficient too?
I didn't use the function get_m()
because I'm in the same class, they used it, but it worked for me, is that ok?
Thank you
As they have explained to you, a reflexive matrix is one in which the elements of the main diagonal are 1.
This implies, aside from what @Solrac commented :
Possible implementation:
And now the questions:
If you have a loop such that:
You are
m_*n_
iterating, whereas if the loop looks like this:With m_ iterations you get the same result. It seems obvious to think that
m_
iterations are much less thanm_*n_
, right? The result is that, effectively, your algorithm will be less efficient... although, incidentally, for what is proposed in the exercise you will not notice any difference.What it would be more accurate to say is that your solution is not correct even though the result was good and the reason is that you are working with variables that have no use (
j
in the second loop). That part not only adds no value to the algorithm but also complicates its readability.Initializing
encontrado
afalse
doesn't make it inefficient... it prevents the program from working properly.If the objective of the algorithm is to guarantee that the main matrix is 1, then the program must fail if a different number is found.
What you are doing is assuming that the matrix is not going to be adjacent and, when you find a 1, decide that it is going to be adjacent. Said with an example, your algorithm detects the following as adjacent matrix:
The relationship described in a matrix is reflexive if the main diagonal of the matrix contains only 1's (ones). Therefore, what must be traversed is the main diagonal.
In your code:
m_
directly is fine, since the function belongs to the class.encontrado
does not make the code inefficient.Try this:
NOTE: the start and end condition of the index
i
will be determined according to how your array is stored.