0

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?

Community
  • 1
  • 1
User12
  • 3
  • 1

1 Answers1

1

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Thanks David! That makes a ton of sense. If I wanted to stick with the method of making sure all people voted the minimum, as opposed to looking for someone who did not, how could I modify my code in Part 2 to ensure that it still gives me the right result? You can simply give me a pseudo code if you'd like. Thanks! – User12 Jun 13 '20 at 22:41
  • @User12 You would wind up turning it into the code in part 1. – David Schwartz Jun 14 '20 at 22:22