CSCI 103 - Spring 2024 Introduction to Programming

Sample MT2 (Codio) Solutions

new_cstr problem solution

#include <iostream>
#include <algorithm> 
//********************
// You may NOT add other #includes
// You have to write other desired
//  functionality yourself
//********************
using namespace std;


// Complete the following function
//
// This function should return a **new**, correctly-formatted C-String
//  with size "length" (given by the input argument) and 
//  containing the substring from str[startPos] to str[startPos+length-1].
//
//  str         is a valid C-string. It should not be altered
//  startPos    starting index/position of the desired substring
//  length      is the desired length of the substring
//
// Return the pointer (start address) of the new array containing
//  the substring. You should always return a pointer to a valid
//  C-string even if the input arguments are invalid...see examples
//  below.
//
// ** You may NOT use any library functions in your implementation **
//
// Example 1:  csubstr("Hello world", 3, 4) should return "lo w"
// Example 2:  csubstr("USC", 0, 2) should return "US"
//
// if any part of the specified range of the substring falls out of
//  bounds of the input string, return a substring containing only
//  the valid portion.
//
// Example 3:  csubstr("USC", 1, 10) should return just "SC"
//                  since the length is beyond the end of "USC"
//
//

char* new_csubstr(char* str, int startPos, int length)
{
  int mylen=0;
  while(str[mylen] != '\0') mylen++;

  // we might waste some memory if `length` characters
  // cannot be extracted, but let's use the length given us
  char* retval = new char[length+1];
  int oidx = 0;
  int maxIndex = min(startPos+length, mylen);
  for(int i=startPos; i < maxIndex; i++){
    retval[oidx] = str[i];
    oidx++;
  }
  retval[oidx] = '\0';
  return retval;

}


//**************************************
// Do not change these 2 lines and don't
// add any lines between them and main()
//**************************************
#ifndef AUTO_TEST
#define AUTO_TEST
int main(int argc, char* argv[])
{
  //*********************************************************
  // Make test calls to your function here
  //*********************************************************
  char* result;
  result = new_csubstr("Hello world", 3, 4);
  cout << result << endl;
  delete [] result;

  result = new_csubstr("USC", 0, 2);
  cout << result << endl;
  delete [] result;

  return 0;  
}
//****************************************
// Do not change the following line
//****************************************
#endif

election.cpp solutions

#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>

using namespace std;

// Stores a state's name and how many
// electoral votes that state has
struct StateElectoralInfo{
  string state;
  int elecVotes;
};

// Complete the following function
//
// This function should search/find the target state name
//  in an array of StateElectoralInfo structs
//  and return its index in the array
//
//  state_info  is an array of filled in StateElectoralInfo structs
//  len         is the length/size of the state_info array
//  target      is the state name you need to find
//
// Return the index in the state_info array
//  of the element that matches the stateName string.
// Return -1 is the stateName does not appear in the array

int findIndexOfState(StateElectoralInfo state_info[], int len, string stateName)
{
  for(int i=0; i < len; i++){
    if(state_info[i].state == stateName){
      return i;
    }
  }
  return -1;
}


//**************************************
// Do not change these 2 lines and don't
// add any lines between them and main()
//**************************************
#ifndef AUTO_TEST
#define AUTO_TEST
int main(int argc, char* argv[])
{
  //*********************************************************
  // Use these declarations to store the appropriate answers.
  // Our 'couts' at the bottom expect these variables to 
  //  be set correctly by the end of your program.
  //*********************************************************

  int a_elec_votes=0; // Total candidate 1 electoral college votes from all states
  int b_elec_votes=0; // Total candidate 2 electoral college votes from all states
  
  if(argc < 3){
    cout << "Not enough command line arguments." << endl;
    cout << "Usage: ./election <electoral college data file> <voting data file>" << endl;
    return -1;
  }

  const string elecFileErrorMsg = "Electoral college file not found.";
  const string voterFileErrorMsg = "Voter totals file not found.";

  //*********************************************************
  // Add your own variable declarations and write your code
  // below.
  //*********************************************************
  ifstream ec(argv[1]);
  if(ec.fail())
    {
      cout << elecFileErrorMsg << endl;
      return -1;
    }
  ifstream votes(argv[2]);
  if(votes.fail())
    {
      cout << voterFileErrorMsg << endl;
      return -1;
    }
  
  StateElectoralInfo* state_info;
  
  int numStates;
  ec >> numStates;
  if(ec.fail()){
    cout << "Can't read the number of states" << endl;
    return -1;
  }
  
  state_info = new StateElectoralInfo[numStates];

  for(int i=0;i<numStates;i++)
    {
      ec >> state_info[i].state >> state_info[i].elecVotes;
    }
  
  int aNum, bNum;
  string currState;
  for(int i=0;i<numStates;i++)
    {
      votes >> aNum >> bNum >> currState;
      int state_index = findIndexOfState(state_info, numStates, currState);
      if(aNum > bNum){
	      a_elec_votes += state_info[state_index].elecVotes;
      }
      else  {
      	b_elec_votes += state_info[state_index].elecVotes;
      }
    }
  
  delete [] state_info;

  //**************************************
  // Output the final winner in the format:
  //  A (332) beats B (206)
  //**************************************

  if(a_elec_votes > b_elec_votes) {
    cout << "A (" << a_elec_votes << ") beats B (" << b_elec_votes << ")" << endl;
  }
  else {
    cout << "B (" << b_elec_votes << ") beats A (" << a_elec_votes << ")" << endl;
  }

  return 0;  
}
//****************************************
// Do not change the following line
//****************************************
#endif

//****************************************
// You may add code after this if you like
//****************************************