From 5cbcd8a571a152edc0aa09f55fac151433421b03 Mon Sep 17 00:00:00 2001 From: tinnamchoi Date: Thu, 21 Mar 2024 12:27:10 +0800 Subject: [PATCH] fix: preemptively fix potential issue with infinite loop 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 --- example/tests/out.txt | 2 +- src/hare-clark.hpp | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/example/tests/out.txt b/example/tests/out.txt index ea82012..d623820 100644 --- a/example/tests/out.txt +++ b/example/tests/out.txt @@ -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 diff --git a/src/hare-clark.hpp b/src/hare-clark.hpp index e5c1f0f..3d306da 100644 --- a/src/hare-clark.hpp +++ b/src/hare-clark.hpp @@ -75,7 +75,7 @@ class HareClark { std::vector 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) { @@ -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; } };