Reputation: 183
I've been trying to solve an issue I have with the lock_pairs function. I used recursion to validate if we have a path that follows a cycle (basically, follow the losers path to see if it won against another candidate and checking if we get back to the origin point, effectively forming a cycle).
But I have an issue since it returns an error when using check50 to validate my solution, and I'm way too lost to even think what is wrong, I feel I've checked everything and still it doesn't work.
This is the error from check50:
:( lock_pairs skips final pair if it creates cycle
lock_pairs did not correctly lock all non-cyclical pairs
Here's the code:
// To be used in lock_pairs to avoid cycles, true means cycles, false means we good
bool check_cycles(int loser_ind, int winner_ind)
{
// Base case, if the loser path returns to the winner, we have a circle
if (loser_ind == winner_ind)
{
return true;
}
for (int i = 0; i < candidate_count; i++)
{
if (locked[loser_ind][i]) // If the loser has an edge over another candidate, i.e, if the loser candidate won against another candidate
{
return check_cycles(i, winner_ind); // We'll check if that other candidate that lost has a winning path to another candidate
}
}
return false;
}
// Lock pairs into the candidate graph in order, without creating cycles
void lock_pairs(void)
{
// Let's loop on all pairs
for (int i = 0; i < pair_count; i++)
{
// If we didn't created a cycle, we'll register the lock
if (!check_cycles(pairs[i].loser, pairs[i].winner))
{
locked[pairs[i].winner][pairs[i].loser] = true; // It means the i-th pair winner candidate won over i-th pair losing candidate
}
}
return;
}
Upvotes: 0
Views: 297
Reputation: 53
Maybe changing
return check_cycles(i, winner_ind);
to
if (check_cycles(i, winner_ind)){
return true;
}
would fix it
Upvotes: 1