Map<string, double> gerrymanderingRatios(const string &file) {
Map<string, int> countMap;
Map<string, vector<string>> districtVotes; // district : votes
Map<string, string> districtWinner;
Map<string, double> gerryMap; // party : ratio (returned)
double totalVotes = 0.0;
double districtCounter = 0.0;
double ratio = 0.0;
ifstream file_in(file);
if (file_in) {
string line;
string districtName;
string partyVote;
while (file_in >> districtName, getline(file_in, line)) {
stringstream ss(line);
while (ss >> partyVote) {
try {
++countMap[partyVote];
}
catch (out_of_range) {
countMap[partyVote] = 1;
}
districtVotes[districtName].push_back(partyVote);
++totalVotes;
}
string winner;
for (auto looker : districtVotes) {
sort(districtVotes[districtName].begin(), districtVotes[districtName].end());
int max = 0;
for (size_t i = 0; i < districtVotes[districtName].size(); ++i) {
int counter = count(districtVotes[districtName].begin(), districtVotes[districtName].end(), districtVotes[districtName][i]);
if (counter > max) {
max = counter;
winner = districtVotes[districtName][i];
}
}
}
districtWinner[districtName] = winner;
++districtCounter;
}
}
file_in.close();
Map<string, int>::iterator voteCounter = countMap.begin(); // countMap
for (; voteCounter != countMap.end(); ++voteCounter) {
Map<string, string>::iterator partyCounter = districtWinner.begin(); // districtWinner
int districtsWon = 0;
for (; partyCounter != districtWinner.end(); ++partyCounter) {
if (*voteCounter == districtWinner.get(*partyCounter))
++districtsWon;
}
double percentOfVotes = countMap.get(*voteCounter) / totalVotes; // total votes / # of party votes
double percentDistrictsWon = districtsWon / districtCounter; // districts won by party / # of districts
ratio = percentDistrictsWon / percentOfVotes;
gerryMap[*voteCounter] = ratio;
}
return gerryMap;
}
Comments