[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[lmi-commits] [lmi] master b772ca6 2/5: Avert division by zero
From: |
Greg Chicares |
Subject: |
[lmi-commits] [lmi] master b772ca6 2/5: Avert division by zero |
Date: |
Fri, 17 Aug 2018 09:35:39 -0400 (EDT) |
branch: master
commit b772ca60bf377d26b5ca0e09a7be1e58ea5eef5f
Author: Gregory W. Chicares <address@hidden>
Commit: Gregory W. Chicares <address@hidden>
Avert division by zero
---
report_table.cpp | 1 +
report_table_test.cpp | 7 +++++++
2 files changed, 8 insertions(+)
diff --git a/report_table.cpp b/report_table.cpp
index 7d41694..e9638f1 100644
--- a/report_table.cpp
+++ b/report_table.cpp
@@ -49,6 +49,7 @@ std::vector<int> apportion(std::vector<int> const& votes, int
total_seats)
int const cardinality = lmi::ssize(votes);
std::vector<int> seats(cardinality);
int const total_votes = std::accumulate(votes.begin(), votes.end(), 0);
+ if(0 == total_votes) return seats; // Avert division by zero.
std::priority_queue<std::pair<int,int>> queue;
for(int j = 0; j < cardinality; ++j)
{
diff --git a/report_table_test.cpp b/report_table_test.cpp
index b3261c8..580bc8a 100644
--- a/report_table_test.cpp
+++ b/report_table_test.cpp
@@ -118,6 +118,13 @@ void report_table_test::test_apportion()
std::vector<int> const seats2 = {8, 8, 5, 2, 2, 1};
BOOST_TEST(seats2 == apportion(votes1, 26));
+
+ // Test with zero total votes, to make sure that division by zero
+ // is averted.
+
+ std::vector<int> const votes3 = {0, 0, 0};
+ std::vector<int> const seats3 = {0, 0, 0};
+ BOOST_TEST(seats3 == apportion(votes3, 7));
}
void report_table_test::test_bloat()