Runoff is a ranked choice voting system. It has the benefit to provide a winner that better reflect the voters’ preference. To make that work, each voter rank the candidates in a preference list. If any candidate has a majority of the first vote preference, that candidate is declared the winner. If no candidate has more than 50% of the votes, an instant runoff takes place. The candidate that received the least amount of votes is eliminated from the election, anyone that had previously selected that candidate as their first preference now has their second preference considered. The process repeats until one candidate has the majority or the election comes to a tie.

Talking about code, this is how the program should run given 3 candidates and 5 voters:

./runoff Alice Bob Charlie
Number of voters: 5
Rank 1: Alice
Rank 2: Bob
Rank 3: Charlie

Rank 1: Alice
Rank 2: Charlie
Rank 3: Bob

Rank 1: Bob
Rank 2: Charlie
Rank 3: Alice

Rank 1: Bob
Rank 2: Alice
Rank 3: Charlie

Rank 1: Charlie
Rank 2: Alice
Rank 3: Bob

Alice

Distribution Code

Following the method of the last problem, here we receive a distribution code with the everything but the functions already working. I’ve cut it in some parts to take a closer look.

Here we have our global stuff: libraries (I think I did include string.h if not mistaken), two constants for max number of voter and candidates, an empty 2d array called preferences, a structure named candidate with name, votes and a bool value to flag if the candidate is eliminated, the candidates array, two variables for the actual number of voters and candidates and finally our function prototypes.

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

// Max voters and candidates
#define MAX_VOTERS 100
#define MAX_CANDIDATES 9
// preferences[i][j] is jth preference for voter i
int preferences[MAX_VOTERS][MAX_CANDIDATES];
// Candidates have name, vote count, eliminated status
typedef struct
{
    string name;
    int votes;
    bool eliminated;
}
candidate;
// Array of candidates
candidate candidates[MAX_CANDIDATES];
// Numbers of voters and candidates
int voter_count;
int candidate_count;
// Function prototypes
bool vote(int voter, int rank, string name);
void tabulate(void);
bool print_winner(void);
int find_min(void);
bool is_tie(int min);
void eliminate(int min);

#cs50 #learn-programming #newbie-guide #harvard #deep-learning

CS50x Runoff
7.65 GEEK