0

I've tried two different variations of my implementation of the find_min functions and both times two of the requirements on check50 are achieved and only one shows an error.

    Sucesses:
    :) find_min returns minimum number of votes for candidate
    :) find_min returns minimum when all candidates are tied
    Error:
    :( find_min ignores eliminated candidates
        find_min did not identify correct minimum

Here's two variations of my find_min function: (Thanks for your time and help in advance :))

    // variation 1
    int find_min(void)
    {
        int min = voter_count;
        for (int i = 0; i < candidate_count; i++)
        {
            if (candidates[i].eliminated == false)
            {
                min = candidates[i].votes;
                for (int j = 0; j < candidate_count; j++)
                {
                    if (candidates[j].votes <= min)
                    {
                        min = candidates[j].votes;
                    }
                }
            }
    }
        return min;
    }

    // Variation 2
    int find_min(void)
    {
        int min = voter_count;
        for (int i = 0; i < candidate_count; i++)
        {
            min = candidates[i].votes;
            if (candidates[i].eliminated == false)
            {
                if (candidates[i].votes <= min)
                {
                    min = candidates[i].votes;
                }
            }
    }
    
        return min;
    }
2
  • I fixed variation 2 by putting the 'if (candidates[i].eliminated == false' above the 'min = candidates.votes' so that the function first check whether or not the candidates is eliminated and then sets that candidate's vote count as the min and then the other if statement allows the function to check for any other vote count lower than the current. – ehsansth Mar 24 at 7:41
  • One thing I still haven't figured out is Variation 1 and why it doesn't work. – ehsansth Mar 24 at 7:41
0

I think I figured it out and I ran check50 and it all checks out.

In Variation 2, I make the mistake of setting candidates[i].votes as the starting value of min without even verifying if the first candidate is eliminated or not.

If fixed this by slightly changing variation 2 to make sure an if statement first verifies whether or not on the first iteration, the candidates[i].eliminated is false or not and then set min = candidates[i].votes and then I nested another if statement to see if that candidate's vote count is lower than the current min or not and then keep iterating to find the lowest vote count and then return that.

1
  • Can someone explain what's wrong with variation 1 because I can't seem to fully figure out the exact issue with it. TIA :) – ehsansth Mar 24 at 7:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .