CS 106B Midterm: CS 106B Midterm 1 Spring 2013 Solutions
Document Summary
The simplest solution to this problem is simply to count up how many districts were won, along with the total number of votes and votes for the given political party. Given these three values, plus the number of districts, the gerrymandering ratio can be computed directly. double gerrymanderingratio(vector >& districts, string party) { int districtswon = 0; int voteswon = 0; int votestotal = 0; /* compute statistics per-district. foreach (vector district in districts) { /* count how many votes in this district we won. int votesthisdistrict = 0; for (string city in district) { if (city == party) { votesthisdistrict++; /* update total number of cities and total cities we won. votestotal += district. size(); voteswon += votesthisdistirct; /* update total districts won if we won this district. if (votesthisdistrict >= district. size() / 2. 0) { districtswon ++; /* compute fraction of districts we won. double districtratio = double(districtswon) / districts. size();