I am working on the Tideman problem from the CS50 course (see Problem Set 3 – Tideman), and I am having an issue with my lock_pairs
function. The function is intended to lock pairs of candidates without creating cycles, but I am encountering unexpected behavior.
I have implemented the function to iterate over pairs and attempt to lock them in a way that prevents cycles. While my implementation passes certain test cases, I am not confident that it is robust enough to handle all scenarios. I suspect I might be missing something related to cycles.
I have tried to check for cycles manually in my code without recursion (I only realized recursion might be needed after Googling post-implementation), and I was working under the assumption that I could not modify the code outside the provided function definitions (i.e., no additional helper functions).
The course specification allows modifying the lock_pairs
function as long as no cycles are introduced. However, I am unsure if my approach is correct or if I am just getting lucky with my test cases and the candidate orders I’ve tried. I would greatly appreciate feedback on whether this implementation is correct or if there’s a flaw in the logic.
Background:
- Problem set: CS50 Tideman
- The function must lock pairs of candidates into a graph without creating cycles.
- I initially forgot about recursion for cycle detection.
Here’s my current implementation of lock_pairs
:
// Lock pairs into the candidate graph in order, without creating cycles
void lock_pairs(void)
{
int lastloser;
int winnerloser = MAX + 1;
for (int r = 0; r < pair_count; r++)
{
int losercheck[MAX] = {0};
// Check each locked pair if false (empty), store only the loser index
for (int i = 0; i < candidate_count; i++)
{
for (int j = 0; j < candidate_count; j++)
{
if (locked[i][j] == false)
{
losercheck[j]++;
}
}
}
lastloser = 0;
// Check how many currently are all empty by comparing to candidate count
for (int j = 0; j < candidate_count; j++)
{
if (losercheck[j] == candidate_count)
{
// Store quantity of empty loser columns in lastloser
lastloser++;
}
}
// If last loser == 1, leave it blank to declare a winner
if (lastloser == 1)
{
for (int j = 0; j < candidate_count; j++)
{
if (losercheck[j] == candidate_count)
{
winnerloser = j;
}
}
}
if (pairs[r].loser != winnerloser)
{
locked[pairs[r].winner][pairs[r].loser] = true;
}
}
return;
}
My Question:
- Is this implementation correct for ensuring no cycles are created while locking pairs?
- Is the manual checking method I’ve employed effective, or is recursion necessary for checking cycles, as suggested in the problem hints?
- Are there any edge cases where this implementation might fail that I might not have tested?
I am happy to provide additional context if necessary. Thanks in advance for your help!
sn0wii_roo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.