Find winner of an election where votes are represented as candidate names in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the election winner. We will have an array of votes that each candidate got in the election. Let's see an example.

Input 

{"A", "B", "C", "B", "A", "C", "D", "D", "A", "B", "D", "B", "A", "C", "D"}

Output 

A

Here, A and B got the same number of votes. In that case, we have to select the winner based on the alphabetical order of their names.

Let's see the steps to solve the problem.

  • Initialize an array of string with dummy data.

  • Initialize a map with string as key and int as value.

  • Iterate over the votes array and count the each member votes. Use the map to store the votes count.

  • We have votes count with us. To find the election winner, iterate over the map and find the key with max votes.

  • If two members got the same votes, then check for their names.

  • Print the winner.

Example

Let's see the code.

 Live Demo

#include "bits/stdc++.h"
using namespace std;
void findElectionWinner(string votes[], int total_votes) {
   map<string, int> candidate_votes_count;
   // counting each person votes
   for (int i = 0; i < total_votes; i++) {
      candidate_votes_count[votes[i]]++;
   }
   // finding winner
   int max_votes = 0;
   string election_winner;
   for (auto& entry : candidate_votes_count) {
      string key = entry.first;
      int val = entry.second;
      // checking the votes with max votes
      if (val > max_votes) {
         // updating max votes and member
         max_votes = val;
         election_winner = key;
         // comparing the name if the votes are equal
      }
      else if (val == max_votes && election_winner > key) {
         election_winner = key;
      }
   }
   cout << election_winner << endl;
}
int main() {
   string votes[] = {"A", "B", "C", "B", "A", "C", "D", "D", "A", "B", "D", "B", "A"};
   findElectionWinner(votes, 13);
   return 0;
}

Output

If you execute the above program, then you will get the following result.

A

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 29-Dec-2020 10:48:58
Advertisements