Cs50 Tideman Solution -
// Number of candidates int candidate_count;
Here is how I cracked it, and the specific logic that finally made the "click" happen.
void lock_pairs(void)
if (preferences[i][j] > preferences[j][i])
Recursion checks if the loser can eventually beat the winner via other locked pairs. Cs50 Tideman Solution
CS50’s problem set is widely considered one of the most challenging assignments in Harvard's introduction to computer science. It requires you to implement a ranked-choice voting system that guarantees a fair winner using the Tideman alternative (also known as the Ranked Pairs method).
In this problem, you will implement the Tideman voting system. You will be given a list of candidates and a list of votes, where each vote is a list of ranked candidates. Your task is to determine the winner of the election.
bool cycle(int winner, int loser)
Once you get it working, you’ll feel a deep sense of accomplishment — and a much stronger grasp of recursion and graph traversal. // Number of candidates int candidate_count; Here is
// Only lock if it doesn't create a cycle if (!will_create_cycle(winner, loser))
You’ll have:
bool is_path(int start, int end)
Lock: Create a directed graph by "locking in" pairs, provided they do not create a cycle. It requires you to implement a ranked-choice voting
void sort_pairs(void) for (int i = 0; i < pair_count - 1; i++) for (int j = 0; j < pair_count - i - 1; j++) // Compare margins: pairs[j] vs pairs[j+1] int margin1 = preferences[pairs[j].winner][pairs[j].loser] - preferences[pairs[j].loser][pairs[j].winner]; int margin2 = preferences[pairs[j+1].winner][pairs[j+1].loser] - preferences[pairs[j+1].loser][pairs[j+1].winner]; if (margin1 < margin2) // Swap pairs pair temp = pairs[j]; pairs[j] = pairs[j+1]; pairs[j+1] = temp; Use code with caution. 5. lock_pairs Function (The Hardest Part)
The algorithm works in four major stages: , Sort , Lock , and Winner Selection . 1. Tallying Votes ( vote and record_preferences ) First, the program must record each voter's ranking.
void 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; Use code with caution.
string name = get_string("Rank %i: ", j + 1); if (!vote(j, name, ranks))