booleancs50boolean-logicboolean-operationsbooleanquery

Boolean Logic Question - Two different methods


I figured out two different ways of solving a question, and while both seem logical, only one of them works. Basically, the function will return true if all remaining candidates who have not been eliminated have the same minimum number of votes and false otherwise. The two methods are the following:

1

bool is_tie(int min)
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (!candidates[i].eliminated)
        {
            if (candidates[i].votes != min)
                return false;
        }
    }
    return true;   
}

2

bool is_tie(int min)
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (!candidates[i].eliminated)
        {
            if (candidates[i].votes == min)
                return true;
        }
    }
    return false;   
}

I do not see any logical difference between the two code functions above. Why is Number 2 wrong then?


Solution

  • Your code marked 1 returns false if any one candidate voted anything other than the minimum.

    Your code marked 2 returns true if any one candidate voted the minimum.

    So consider the case where there are two candidates, one who voted the minimum and one who didn't. Your code marked 1 returns false since one candidate voted other than the minimum. Your code marked 2 returns true since one candidate did vote the minimum.