Skip to content

Commit

Permalink
fix: preemptively fix potential issue with infinite loop
Browse files Browse the repository at this point in the history
in cases where the number of remaining candidates is lower than the number of vacancies, it is
possible that the program gets into an infinite loop
  • Loading branch information
tinnamchoi committed Mar 21, 2024
1 parent e5fee7a commit 5cbcd8a
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 2 deletions.
2 changes: 1 addition & 1 deletion example/tests/out.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
Enter the number of vacancies: Enter the number of votes: Enter the number of candidates: Enter the names of the candidates (space-separated): Enter the ballots (space-/line-separated):

Elected candidates: JoseBishop AntonyMorrow JadenWall VanessaPacheco
Elected candidates: JoseBishop JadenWall AntonyMorrow VanessaPacheco
5 changes: 4 additions & 1 deletion src/hare-clark.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class HareClark {
std::vector<double> votes(candidates.size()); // Current value of votes for each candidate
for (const auto& [ballot, weight] : ballots_with_weights) votes[ballot.back()] += weight;

while (number_of_vacancies) {
while (number_of_vacancies < candidates.size() - unavailable_candidates.size()) {
int winner = -1;
int loser = -1;
for (int i = 0; i < candidates.size(); ++i) {
Expand All @@ -97,6 +97,9 @@ class HareClark {
votes[loser] = -1;
}
}
if (number_of_vacancies) {
for (int i = 0; i < candidates.size(); ++i) if (!unavailable_candidates.count(i)) elected_candidates.push_back(candidates[i]);
}
return elected_candidates;
}
};

0 comments on commit 5cbcd8a

Please sign in to comment.