// SASSolver.cpp // tom bailey 15 oct 04 // tom bailey 16 oct 08 // Define a base class and several concrete classes of objects // that solve the best subarray sum problem for a sequence // stored in a vector. #include "SASSolver.h" #include using std::cout; using std::cin; using std::endl; using std::max; void SASSolver:: description( ostream & outfile ) const { outfile << "SAS Base Class"; } void SASOne:: description( ostream & outfile ) const { outfile << "SAS One"; } //Fill in the code // Return the greatest sum of any contiguous subarray of v. double SASOne:: bestSum( const vector & v ) { return 42; } //Fill in the code // Return the sum of the elements referenced by begin..offEnd. template< typename IT > double SASOne:: sum( IT begin, IT offEnd ) { return 42; } // Construct a ResType appropriate for an empty segment. ResType:: ResType() { best = 0.0; bestToLeft = 0.0; bestToRight = 0.0; sum = 0.0; } // Construct a ResType appropriate for the singleton // segment referenced by iter. template< typename IT > ResType:: ResType( IT iter ) { sum = *iter; best = max( 0.0, sum ); bestToLeft = best; bestToRight = best; } //Fill in the code // Mutate this ResType so that it describes the segment // consisting of the adjacent segments initially // described by this ResType and by rhs. ResType ResType:: operator += ( const ResType & rhs ) { return *this; } ResType operator + ( const ResType & lhs, const ResType & rhs ) { ResType result( lhs ); result += rhs; return result; } double ResType:: bestSAS() const { return best; } void SASFour:: description( ostream & outfile ) const { outfile << "SAS Four"; } // Return the greatest sum of any contiguous subarray of v. double SASFour:: bestSum( const vector & v ) { return bestSum( v.begin(), v.end() ).bestSAS(); } //Fill in the code // Return the ResType describing the vector segment // referenced by the iterators begin..offEnd. template< typename IT > ResType SASFour:: bestSum( IT begin, IT offEnd ) { // If the segment is empty // return the appropriate ResType. // If the segment is a single element // return the appropriate ResType. // If the segment is large // find the bestSum for each half, // combine them, and return the result. return ResType(); } SASSolver & getAlgorithm() { cout << "Enter Algorithm choice [One,Four]: "; string choice; cin >> choice; cout << choice << endl; if( choice == "One" ) return * new SASOne; else if( choice == "Four" ) return * new SASFour; else { cout << "choice not found" << endl; exit(1); } } ostream & operator<<( ostream & outfile, const SASSolver & sas ) { sas.description( outfile ); return outfile; }