Whilst writing my code for Tideman in Problem Set 3, I had many problems with the lock pair function, as I am very new to coding. Some research I did online also showed that this question is notoriously hard given that it appears in just week 3.
My code is as follows:
bool iscycle(int index, bool visited[])
{
if (visited[index])
{
return true;
}
visited[index] = true;
for (int i = 0; i < candidate_count; i++)
{
if (locked[index][i] && iscycle(i, visited))
{
return true;
}
}
return false;
}
// Lock pairs into the candidate graph in order, without creating cycles
void lock_pairs(void)
{
for (int i = 0; i < pair_count; i++)
{
locked[pairs[i].winner][pairs[i].loser] = true;
bool visited[candidate_count];
for (int j = 0; j < candidate_count; j++)
{
visited[j] = false;
}
if (iscycle(i, visited))
{
locked[pairs[i].winner][pairs[i].loser] = false;
}
}
return;
}
The only error is as follows:
:( lock_pairs skips final pair if it creates cycle
lock_pairs did not correctly lock all non-cyclical pairs
I have been staring at my code for days and am simply unable to wrap my head around what is wrong. In fact, many of the codes I have seen for the lock_pairs function on this site usually has issues with the middle pair, so I am truly intrigued by what the logical flaw is in mine.