CS50x Plurality

Photo by Arnaud Jaegers on Unsplash
$ ./plurality Alice Bob Charlie
Number of voters: 4
Vote: Alice
Vote: John
Invalid Vote.
Vote: Charlie
Vote: Alice
Alice
#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();
}
bool vote(string name)
{
for (int n = 0; n < candidate_count; n++)
{
if (strcmp(name, candidates[n].name) == 0)
{
candidates[n].votes++;
return true;
}
}
return false;
}
void print_winner(void)
{
// TODO
int winner = 0;
for (int v = 0; v < candidate_count; v++)
{
if (candidates[v].votes > winner)
{
winner = candidates[v].votes;
}
}
for (int w = 0; w < candidate_count; w++)
{
if (candidates[w].votes == winner)
{
printf("%s\n", candidates[w].name);
}
}
}
Results generated by style50 v2.7.4
Looks good!
Results for cs50/problems/2020/x/plurality generated by check50 v3.1.2
:) plurality.c exists
:) plurality compiles
:) vote returns true when given name of first candidate
:) vote returns true when given name of middle candidate
:) vote returns true when given name of last candidate
:) vote returns false when given name of invalid candidate
:) vote produces correct counts when all votes are zero
:) vote produces correct counts after some have already voted
:) vote leaves vote counts unchanged when voting for invalid candidate
:) print_winner identifies Alice as winner of election
:) print_winner identifies Bob as winner of election
:) print_winner identifies Charlie as winner of election
:) print_winner prints multiple winners in case of tie
:) print_winner prints all names when all candidates are tied

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store