Skip to content

Instantly share code, notes, and snippets.

@deeunix
Last active June 4, 2024 01:20
Show Gist options
  • Save deeunix/d9523f86b7499ba880055f836b48ba6d to your computer and use it in GitHub Desktop.
Save deeunix/d9523f86b7499ba880055f836b48ba6d to your computer and use it in GitHub Desktop.
my Cs50 plurality solution
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Max number of candidates
#define MAX 9
// Candidates have name and vote count
typedef struct
{
string name;
int votes;
}
candidate;
// Array of candidates
candidate candidates[MAX];
// Number of candidates
int candidate_count;
// Function prototypes
bool vote(string name);
void print_winner(void);
int main(int argc, string argv[])
{
// Check for invalid usage
if (argc < 2)
{
printf("Usage: plurality [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].name = argv[i + 1];
candidates[i].votes = 0;
}
int voter_count = get_int("Number of voters: ");
// Loop over all voters
for (int i = 0; i < voter_count; i++)
{
string name = get_string("Vote: ");
// Check for invalid vote
if (!vote(name))
{
printf("Invalid vote.\n");
}
}
// Display winner of election
print_winner();
}
// Update vote totals given a new vote
bool vote(string name)
{
//Loop through the Candidate count
for (int i = 0; i < candidate_count; i++)
{
//check if candidate is similar to what is user's vote
if (strcmp(candidates[i].name, name) == 0)
{
//if similar to what user vote for, then increase the specific candidate vote and return true
candidates[i].votes++;
return true;
}
}
//else if not similar to candidate vote return false.....and print invalid vote
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
//Create and variable and set it to 0
int maximum_vote = 0;
//iterate over list of candidate
for (int i = 0; i < candidate_count; i++)
{
//check for candidate votes that are greater than maximum_vote and set them to maximum_vote
if (candidates[i].votes > maximum_vote)
{
maximum_vote = candidates[i].votes;
}
}
//iterate over list of candidate
for (int i = 0; i < candidate_count; i++)
{
//check for candidate votes that are equal to maximum vote and print them as you go
if (candidates[i].votes == maximum_vote)
{
printf("%s\n", candidates[i].name);
}
}
return;
}
@AbrahamZayed
Copy link

wow, just wow. get's the job and done and beautifully written. great job mate!!

@czernous
Copy link

Oh man, looks like I've overengineered mine. Yours looks a lot less convoluted. I wrote a sort function to sort the array of candidates by votes and then did something like this

{
    sort_array(arr, MAX);

    for (int i = candidates_length - 1; i >= 0; i--)
    {

        if (arr[i - 1].votes < arr[i].votes)
        {
            printf("%s\n", arr[i].name);
            break;
        }
        else if (arr[i - 1].votes == arr[i].votes)
        {
            printf("%s\n", arr[i].name);
        }
    }
}

@UppalRahi
Copy link

thanks it helps a lot.

@Jamesthe36
Copy link

Love it!

@TarekAykour
Copy link

I once again dissapointed myself.

@jaredbradley243
Copy link

This is great! Fantastic job.

@j54j6
Copy link

j54j6 commented Jun 28, 2022

Oh man you saved my day :D - my code dont work for like 2 hours and i can't fix the issue... - Tried to convert strings to all lower and checked inputs all wrong... so i checked online, first i thought this post is my code and cs50 had redirected me to my own submit or whatever but you have pretty the same code like me ^^ (except for the comments :) )

In case anyone else is stupid like me - mind the missing space in "printf("%s\n", candidates[i].name);" - this costs me 2 hours XD


bool vote(string name)
{
    // TODO

    //check for vote
    for(int i = 0; i < MAX; i++)
    {
        if(candidates[i].name != NULL)
        {
            string currentName = candidates[i].name;

            if(strcmp(currentName, name) == 0)
            {
                //Canidate found
                candidates[i].votes += 1;
                return true;
            }
        }

    }
    //No canidate found
    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    int maxNumber = 0;
    for(int i = 0; i < MAX; i++)
    {
        int currentVotes = candidates[i].votes;

        if(currentVotes > maxNumber)
        {
            maxNumber = currentVotes;
        }
    }

    for(int i = 0; i < MAX; i++)
    {
        int currentVotes = candidates[i].votes;

        if(currentVotes == maxNumber)
        {
            if(candidates[i].name != NULL)
            {
                printf("%s\n", candidates[i].name);
            }
        }
    }
}

@Ficabral10
Copy link

Hello guys!
#include <cs50.h>
#include <stdio.h>
#include <string.h>

#define MAX 9

// Candidates have name and vote count
typedef struct
{
string name;
int votes;
}
candidate;

// Array of candidates
candidate candidates[MAX];

// Number of candidates
int candidate_count;

// Function prototypes
bool vote(string name);
void print_winner(void);

int main(int argc, string argv[])
{
// Check for invalid usage
if (argc < 2)
{
printf("Usage: plurality [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].name = argv[i + 1];
    candidates[i].votes = 0;
}

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

// Loop over all voters
for (int i = 0; i < voter_count; i++)
{
    string name = get_string("Vote: ");

    // Check for invalid vote
    if (!vote(name))
    {
        printf("Invalid vote.\n");
    }
}

// Display winner of election
print_winner();

}

// Update vote totals given a new vote
bool vote(string name)
{

// to vote we must count each vote and
// give that vote to the correct candidate
for (int currCandidate = 0; currCandidate < candidate_count; currCandidate++) {

    // c has a function called strcmp that
    // compares two strings, most languages
    // have built in features like this
    if (strcmp(name, candidates[currCandidate].name) == 0) {
        // this will take the candidate we are
        // currently iterating over and add 1
        // to their vote count
        candidates[currCandidate].votes++;

        // completes the condition of our function
        // that states that we'll return a bool
        return true;
    }
}

// TODO
// we must return false because in the main function
// we check for true or false
return false;

}

// Print the winner (or winners) of the election
void print_winner(void)
{

int topCandidateNumberOfVotes = 0;

// keeps track of the candidate we are looking at
int currCandidate = 0;
while(currCandidate < candidate_count)
{
    if(topCandidateNumberOfVotes < candidates[currCandidate].votes)
    {
        topCandidateNumberOfVotes = candidates[currCandidate].votes;
    }

    // to go over to the next candidate
    currCandidate++;
}


// I've already declared currCandidate above so no need to redeclare
// and I'm resetting this to 0 to save some RAM :)
// extra variables do add to our space complexity
for (currCandidate = 0; currCandidate < candidate_count; currCandidate++)
{
    if(candidates[currCandidate].votes == topCandidateNumberOfVotes)
    {
        printf("%s\n", candidates[currCandidate].name);
    }
}

// TODO
return;

}
This is my code and everytime i do check50 it tells me its wrong, what sould I change.

@7ossama7med
Copy link

thanks very much

@zoro-io
Copy link

zoro-io commented Mar 30, 2023

Damn, man. Thank you for posting this. The solution to print candidates who shared the maximum vote was quite elegant. I tried to store an array of winner indexes and store the winner or all candidates who tied in the array and print each candidates name who's index was stored in the array and it worked but was so damn confusing to debug. Simplicity is best.

Great job, man.

@nealxu0
Copy link

nealxu0 commented Aug 7, 2023

I hate myself. I thought candidate_count was initialized inside main and didn't realize candidate_count was initialized at the top so i spent so much time fighting check50 by using other methods to basically use candidate_count in a roundabout way until your post made me realize that. Thank you.

Copy link

ghost commented Aug 26, 2023

thank you so much for this

@Keniba1
Copy link

Keniba1 commented Oct 1, 2023

I write the same thing but when I run the code after every vote
it shows me invalid vote and don't show me the winner

@kingaslomin
Copy link

do you have "return true" after "candidates[i].votes++;" in the vote function?

@prophecy6
Copy link

it does that for me too I don't know how to fix it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment