1

I'm getting segmentation fault due to my swap function I believe - but can't figure out where it comes from.

#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Max number of candidates
#define MAX 9

// preferences[i][j] is number of voters who prefer i over j
int preferences[MAX][MAX];

// locked[i][j] means i is locked in over j
bool locked[MAX][MAX];

// Each pair has a winner, loser
typedef struct
{
    int winner;
    int loser;
}
pair;

// Array of candidates
string candidates[MAX];
pair pairs[MAX * (MAX - 1) / 2];

int pair_count;
int candidate_count;

// Function prototypes
bool vote(int rank, string name, int ranks[]);
void record_preferences(int ranks[]);
void add_pairs(void);
void sort_pairs(void);
void lock_pairs(void);
void print_winner(void);
void swap (pair *xp, pair *yp);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: tideman [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i] = argv[i + 1];
    }

    // Print candidates

    printf("candidates are: \n");
        for (int i = 0; i < candidate_count; i++)
    {
        printf("%s %i \n", candidates[i], i);
    }

    // Clear graph of locked in pairs
    for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            locked[i][j] = false;
        }
    }

    pair_count = 0;
    int voter_count = get_int("Number of voters: ");

    // Query for votes
    for (int i = 0; i < voter_count; i++)
    {
        // ranks[i] is voter's ith preference
        int ranks[candidate_count];

        // Query for each rank
        for (int j = 0; j < candidate_count; j++)
        {
            string name = get_string("Rank %i: ", j + 1);

            if (!vote(j, name, ranks))
            {
                printf("Invalid vote.\n");
                return 3;
            }
        }

        record_preferences(ranks);

        printf("\n");
    }

    // Print preferences array
    for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
        printf("%i ", preferences[i][j]);
        }
        printf("\n");
    }

    add_pairs();
    sort_pairs();
    lock_pairs();
    print_winner();
    return 0;
}

// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (strcmp(candidates[i], name) == 0)
        {
            ranks[rank] = i;
            return true;
        }

    }
    // TODO
    return false;
}

// Update preferences given one voter's ranks
void record_preferences(int ranks[])
{
for (int i = 0; i < candidate_count - 1; i++)
{
    for (int j = i + 1; j < candidate_count; j++)
    {
        preferences[ranks[i]][ranks[j]]++;
    }
}
    // TODO
    return;
}


// Record pairs of candidates where one is preferred over the other
void add_pairs(void)
{
    for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            if (preferences[i][j] > preferences[j][i])
            {
                pairs[pair_count].winner = i;
                pairs[pair_count].loser = j;
                pair_count++;
            }
            else if (preferences[i][j] < preferences[j][i])
            {
                pairs[pair_count].winner = j;
                pairs[pair_count].loser = i;
                pair_count++;
            }
        }
    }

    // Print out first 3 pairs for later check
    printf("pair 0: winner = %i pair 0: looser = %i\n", pairs[0].winner, pairs[0].loser);
    printf("pair 1: winner = %i pair 1: looser = %i\n", pairs[1].winner, pairs[1].loser);
    printf("pair 2: winner = %i pair 2: looser = %i\n", pairs[2].winner, pairs[2].loser);

    // TODO
    return;
}

// Sort pairs in decreasing order by strength of victory
void sort_pairs(void)
{
    for (int i = 0; i < pair_count - 2; i++)
    {
        for (int j = i + 1; pair_count - 1; j++)
        {
            int p1wnr = pairs[i].winner;
            int p1lsr = pairs[i].loser;
            int p1diff = preferences[p1wnr][p1lsr] - preferences[p1lsr][p1wnr];

            int p2wnr = pairs[j].winner;
            int p2lsr = pairs[j].loser;
            int p2diff = preferences[p2wnr][p2lsr] - preferences[p2lsr][p2wnr];

            if (p2diff > p1diff)
            {
                swap(&pairs[i], &pairs[j]);
            }
        }
    }

    ///Check that pairs have been sorted
    printf("pair 0: winner = %i pair 0: looser = %i\n", pairs[0].winner, pairs[0].loser);
    printf("pair 1: winner = %i pair 1: looser = %i\n", pairs[1].winner, pairs[1].loser);
    printf("pair 2: winner = %i pair 2: looser = %i\n", pairs[2].winner, pairs[2].loser);
     // TODO
    return;
}

// Lock pairs into the candidate graph in order, without creating cycles
void lock_pairs(void)
{
    // TODO
    return;
}

/////////// ADDED FUNCTIONS //////////////////

// Print the winner of the election
void print_winner(void)
{
    // TODO
    return;
}

// Swap function
void swap (pair *xp, pair *yp)
{
    pair temp = *xp;
    *xp = *yp;
    *yp = temp;
}
1

1 Answer 1

1

If anyone else find this thread and have the same problem, I'll post the code after I solved it:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Max number of candidates
#define MAX 9

// preferences[i][j] is number of voters who prefer i over j
int preferences[MAX][MAX];

// locked[i][j] means i is locked in over j
bool locked[MAX][MAX];

// Each pair has a winner, loser
typedef struct
{
    int winner;
    int loser;
}
pair;

// Array of candidates
string candidates[MAX];
pair pairs[MAX * (MAX - 1) / 2];

int pair_count;
int candidate_count;

// Function prototypes
bool vote(int rank, string name, int ranks[]);
void record_preferences(int ranks[]);
void add_pairs(void);
void sort_pairs(void);
void lock_pairs(void);
void print_winner(void);
void swap (pair *xp, pair *yp);
int check_winner(pair thispair, int current_winner);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: tideman [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i] = argv[i + 1];
    }

    // Print candidates

    printf("\n");
    printf("candidates are: \n");
        for (int i = 0; i < candidate_count; i++)
    {
        printf("Candidate: %s has place: %i \n", candidates[i], i);
    }
    printf("\n");

    // Clear graph of locked in pairs
    for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            locked[i][j] = false;
        }
    }

    pair_count = 0;
    int voter_count = get_int("Number of voters: ");

    // Query for votes
    for (int i = 0; i < voter_count; i++)
    {
        // ranks[i] is voter's ith preference
        int ranks[candidate_count];

        // Query for each rank
        for (int j = 0; j < candidate_count; j++)
        {
            string name = get_string("Rank %i: ", j + 1);

            if (!vote(j, name, ranks))
            {
                printf("Invalid vote.\n");
                return 3;
            }
        }

        record_preferences(ranks);

        printf("\n");
    }

    // Print preferences array
    printf("PREFERENCES ARRAY\n");
    for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
        printf("%i ", preferences[i][j]);
        }
        printf("\n");
    }

    add_pairs();
    sort_pairs();
    lock_pairs();
    print_winner();
    return 0;
}

// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (strcmp(candidates[i], name) == 0)
        {
            ranks[rank] = i;
            return true;
        }

    }
    // TODO
    return false;
}

// Update preferences given one voter's ranks
void record_preferences(int ranks[])
{
for (int i = 0; i < candidate_count - 1; i++)
{
    for (int j = i + 1; j < candidate_count; j++)
    {
        preferences[ranks[i]][ranks[j]]++;
    }
}
    // TODO
    return;
}


// Record pairs of candidates where one is preferred over the other
void add_pairs(void)
{
    printf("\n");
    printf("ADDING PAIRS TO PAIRS ARRAY\n");
    for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            if (preferences[i][j] > preferences[j][i])
            {
                printf("Preferences[%i][%i] = %i is bigger than Preferences[%i][%i] = %i\n", i, j, preferences[i][j], j, i, preferences[j][i]);
                pairs[pair_count].winner = i;
                printf("Winner is: %s\n", candidates[i]);
                pairs[pair_count].loser = j;
                printf("Loser is: %s\n", candidates[j]);
                pair_count++;
                printf("pair_count = %i\n", pair_count);
                printf("\n");

            }
        }
    }
    printf("\n");


    // TODO
    return;
}

// Sort pairs in decreasing order by strength of victory
void sort_pairs(void)
{

    ///Print pairs before sort
    printf("BEFORE SORT\n");
    for (int i = 0; i < pair_count; i++)
    {
        int wnr = pairs[i].winner;
        int lsr = pairs[i].loser;
        int diff = preferences[wnr][lsr] - preferences[lsr][wnr];
        printf("pair %i: winner candidate = #%i with %i votes, loser candidate = #%i with %i votes - diff = %i\n", i, pairs[i].winner, preferences[wnr][lsr], pairs[i].loser, preferences[lsr][wnr], diff);
    }
    printf("\n");

    //Sort pairs

    for (int i = 0; i < pair_count; i++)
    {
        for (int j = i + 1; j < pair_count; j++)
        {
            printf("\n");
            printf("i: %i, j: %i\n", i, j);
            int p1wnr = pairs[i].winner;
            int p1lsr = pairs[i].loser;
            int p1diff = preferences[p1wnr][p1lsr] - preferences[p1lsr][p1wnr];
            printf("p1 diff for pair %i = %i\n", i, p1diff);

            int p2wnr = pairs[j].winner;
            int p2lsr = pairs[j].loser;
            int p2diff = preferences[p2wnr][p2lsr] - preferences[p2lsr][p2wnr];
            printf("p2 diff for pair %i = %i\n", j, p2diff);


            if (p2diff > p1diff)
            {
                printf("***swap was made***\n");
                swap(&pairs[i], &pairs[j]);
            }
        }
    }

    ///Print pairs after sort
    printf("\n");
    printf("AFTER SORT\n");
    for (int i = 0; i < pair_count; i++)
    {
        int wnr = pairs[i].winner;
        int lsr = pairs[i].loser;
        int diff = preferences[wnr][lsr] - preferences[lsr][wnr];
        printf("pair %i: winner candidate = #%i with %i votes, loser candidate = #%i with %i votes - diff = %i\n", i, pairs[i].winner, preferences[wnr][lsr], pairs[i].loser, preferences[lsr][wnr], diff);
    }
    printf("\n");

     // TODO
    return;
}

// Lock pairs into the candidate graph in order, without creating cycles
void lock_pairs(void)
{
    // Set all cells of locked to false as initial value
    for (int i = 0; i < MAX; i++)
    {
        for (int j = 0; i < MAX; i++)
        {
            locked[i][j] = false;
        }
    }

    //Check every pair in pairs[] by check_winner function, if pair don't create a loop, then add pair to locked[]
    for (int i = 0; i < pair_count; i++)
    {
        if (check_winner(pairs[i], pairs[i].winner) == -1)
        {
            locked[pairs[i].winner][pairs[i].loser] = true;
        }
    }

    // TODO
    return;
}

/////////// ADDED FUNCTIONS //////////////////

// Check if loser in input pair is winner in any other pair, if so, check if the loser of that pair is a winner in any other pair
// continue until finding the original winner "original_winner" - then return -2 as this is a loop (result in not locking pair)
int check_winner(pair thispair, int original_winner)
{
    // "Default case" - looser in current pair equals to original willer - return -2 (= don't lock pair)
    if (thispair.loser == original_winner)
    {
        return -2;
    }

    // Go through the pair array to see if the current loser wins in any other pair, use recursion to create
    // chain until above function is satisfied or loop finishes and return -1 (lock pair)
    for (int i = 0; i < pair_count; i++)
    {
        if(pairs[i].winner == thispair.loser)
        {
            return check_winner(pairs[i], original_winner);
        }
    }
    return -1;
}

// Print the winner of the election
void print_winner(void)
{
    // TODO
    return;
}

// Swap function
void swap (pair *xp, pair *yp)
{
    pair temp = *xp;
    *xp = *yp;
    *yp = temp;
}

You must log in to answer this question.

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