Midterm 1 Coding Solutions

Fall 2016

  1. Moonglow
    #include <iostream>
    #include <sstream>
    #include <cstdio>
    using namespace std;
    
    int main() {
       istringstream buffer;
       int score;
       string name;
       string line;
       double avg;
       int numScores;
    
       while (getline(cin, line)) {
          avg = 0;
          numScores = 0;
          buffer.clear();
          buffer.str(line);
          buffer >> name;
          while (buffer >> score) {
             avg += score;
             numScores++;
          }
          printf("%-20s %6.2f\n", name.c_str(), avg/numScores);
       }
    }
        
  2. Voter
    int countBallots(vector<int> &candidates, vector<vector<int> > &ballots) {
      int i, j;
      int winner;
      
      for (i = 0; i < ballots.size(); i++) {
        for (j = 0; j < ballots[i].size(); j++) {
          if (ballots[i][j] == 1) {
            candidates[j]++;
    	break;
          }
        }
      }
      winner = 0;
      for (i = 1; i < candidates.size(); i++) {
         if (candidates[i] > candidates[winner])
            winner = i;
      }
      return winner;
    }