How to make a function that takes two integer vectors and returns a boolean value?

Asked

Viewed 92 times

3

I want to make a function that takes two integer vectors and returns a value Boolean, but when I put the:

return (encontrou);

It keeps error on the variable encontrou. Follows part of my function:

public static bool verificar(int cont, int m1, int m2, int[] Cobertura1, int[] Cobertura2)
{
        bool encontrou;

        for (int i = 0; i <= cont; i++)
        {
            if ((m1 == Cobertura1[i]) & 
                (m2 == Cobertura2[i]) & 
                (m1 == Cobertura2[i]) & 
                (m2 == Cobertura1[i]))
            {
                encontrou = false;
            }
            else
                encontrou = true;
        }

        return (encontrou);
    }

2 answers

5


The error it gives you is due to lack of variable initialization encontrou. Assign a value when declaring it:

public static bool verificar(int cont, int m1, int m2, int[] Cobertura1, int[] Cobertura2)
{
    bool encontrou = false; //agora começa a false
    ...

The reason for the error is because there is no guarantee that the for execute, and so there is also no guarantee that you have placed true or false variable. And the compiler does not allow you to use a local variable, in this case no return, without having previously assigned a value.

You can often structure differently so you don’t have this problem. In your code you are also using & which is the and torque when it should be using && which is the and logical.

5

Now understanding the question better, the code didn’t even compile and the variable has to initialize before using.

But I have other observations.

I think I wanted to use the && and used the & that in some situations may produce a different result. Something like that:

public static bool verificar(int cont, int m1, int m2, int[] Cobertura1, int[] Cobertura2) {
    bool encontrou;
    for (int i = 0; i <= cont; i++) encontrou = !(m1 == Cobertura1[i] && m2 == Cobertura2[i] && m1 == Cobertura2[i] && m2 == Cobertura1[i]);
    return encontrou;
}

On the other hand you might want this:

public static bool verificar(int cont, int m1, int m2, int[] Cobertura1, int[] Cobertura2) {
    for (int i = 0; i <= cont; i++) if (!(m1 == Cobertura1[i] && m2 == Cobertura2[i] && m1 == Cobertura2[i] && m2 == Cobertura1[i])) return true;
    return false;
}

I put in the Github for future reference.

You can reverse the condition to eliminate the negation operator. I don’t even know if I should have this negation, or if the whole condition should be this.

The original algorithm seems strange, it changes state with each different passage, I think it is working by coincidence, depending on the state of the vectors can give unexpected result. But I can’t say without a bigger context.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.