0

So in order to solve lockpairs function, I made a custom function that can detect a cycle (it would return true if it has a cycle, false if it doesn't). My custom functions logic is: Check each pair from pairs list one by one (pairs[0] does it cycle? -> pairs[1] does it cycle? -> etc...) but not actually from the first element because I think first two pairs can't create a loop so I just lock in right away. So how does it check the cycle from 3rd pairs? It will check if the pairs[n].loser matches pairs[i].winner where (0<= i < n) and if the winner exists, check if it's locked and then check if the pairs[i].loser matches with any pairs[k].winner and repeats until the pairs[?].loser matches the initial pairs[n].winner.

From this logic I got my lock pairs function pass all the test from check50 except skipping final pairs.

:( lock_pairs skips final pair if it creates cycle lock_pairs did not correctly lock all non-cyclical pairs

This is my code and please help me find why I am not skipping a final pair if it creates cycle.

void lock_pairs(void)
{   
    for (int i = 0; i < pair_count; i++)
    {
        if (i < 2)
        {
            locked[pairs[i].winner][pairs[i].loser] = true;
            printf("%ith pair locked\n",i + 1);
            continue;
        }
        else
        {
            if (!cycle(i,i))
            {
                printf("%ith pair locked\n", i + 1);
                locked[pairs[i].winner][pairs[i].loser] = true;
                continue;
            }
            else
            {
                printf("repeated. Skip %ith pair\n", i + 1);
                continue;
            }
            
        }
    }
    return;
}    
bool cycle(int x, int y)
{
    for (int i = 0; i < y; i++)
    {
        if (pairs[x].loser == pairs[i].winner)
        {
            if (locked[pairs[i].winner][pairs[i].loser] == true)
            {
                for (int j = 0; j < y; j++)
                {
                    if (pairs[i].loser == pairs[j].winner)
                    {
                        if (locked[pairs[j].winner][pairs[j].loser] == true)
                        {
                            if (pairs[j].loser == pairs[y].winner)
                            {
                                return true;
                            }
                            cycle(j, y);
                        }
                    }
                }
                continue;
            }
        }
    }
    return false;
}

You must log in to answer this question.

Browse other questions tagged .