Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to combine like terms for a templated polynomial class using recursion in c++

I'm teaching my self C++.

I'm trying to combine polynomials. For this I have defined straightforward classes: Polynomial<T>, Term<T> and Coefficient<T> (which may also just be complex<T>) using simple value composition. I have defined the required operator overloads.

Polynomial's compare by sorting their terms (std::sort).

I am working on combineLikeTerms(); This method when called will first call another member method that will sort this vector of Terms. For example:

4x^3 + 5x^2 + 3x - 4 

would be a possible resulting sorted vector.

Question:

I am using two iterators on this vector and Im trying to merge adjacent terms of the same order.

Lets say our initial vector after being sorted is this:

4x^3 - 2x^3 + x^3 - 2x^2 + x ...

after the function completes its iterations the temp stack vector would then look like this 2x^3 + x^3 - 2x^2 + x ... if we look there are still like terms this needs to be refactored again.

How do I do this? I'm thinking of using recursion.

// ------------------------------------------------------------------------- //
// setPolynomialByDegreeOfExponent()
// should be called before combineLikeTerms
template <class T>
void Polynomial<T>::setPolynomialByDegreeOfExponent()
{
    unsigned int uiIndex = _uiNumTerms - 1;
    if ( uiIndex < 1 )
    {
        return;
    }
    struct _CompareOperator_
    {
        bool operator() ( math::Term<T> a, Term<T> b )
        {
            return ( a.getDegreeOfTerm() > b.getDegreeOfTerm() );
        } // operator()
    };
    stable_sort( _vTerms.begin(), _vTerms.end(), _CompareOperator_() );
} // setPolynomialByDegreeOfExponent

// ------------------------------------------------------------------------- //
// addLikeTerms()
template <class T>
bool Polynomial<T>::addLikeTerms( const Term<T>& termA, const Term<T>& termB, Term<T>& result ) const
{
    if ( termA.termsAreAlike( termB ) )
    {
        result = termA + termB;
        return true;
    }
    return false;
} // addLikeTerms

// ------------------------------------------------------------------------- //
// combineLikeTerms()
template <class T>
void Polynomial<T>::combineLikeTerms()
{
    // First We Order Our Terms.
    setPolynomialByDegreeOfExponent();
    // Nothing To Do Then
    if ( _vTerms.size() == 1 )
    {
        return;
    }
    Term<T> result; // Temp Variable
    // No Need To Do The Work Below This If Statement This Is Simpler
    if ( _vTerms.size() == 2 )
    {
        if ( addLikeTerms( _vTerms.at(0), _vTerms.at(1) )
    {
        _vTerms.clear();
            _vTerms.push_back( result );
        }
        return;
    }
    // For 3 Ore More Terms
    std::vector<Term<T>> vTempTerms; // Temp storage
    std::vector<Term<T>>::iterator it = _vTerms.begin();
    std::vector<Term<T>>::iterator it2 = _vTerms.begin()+1;
    bool bFound = addLikeTerms( *it, *it2, result );

    while ( it2 != _vTerms.end() )
    {
        if ( bFound )
        {
            // Odd Case Last Three Elems
            if ( (it2 == (_vTerms.end()-2)) && (it2+1) == (_vTerms.end()-1)) )
            {
                vTempTerms.push_back( result );
                vTempTerms.push_back( _vTerms.back() );
                break;
            }
            // Even Case Last Two Elems
            else if ( (it2 == (_vTerms.end()-1)) && (it == (_vTerms.end()-2)) )
            {
                vTempTerms.push_back( result );
                break;
            }
            else
            {
                vTempTerms.push_back( result );
                it += 2;    // Increment by 2
                it2 += 2;          "
                bFound = addLikeTerms( *it, *it2, result );
            }
            }
                else {
                // Push Only First One
                vTempTerms.push_back( *it );
                it++;   // Increment By 1
                it2++;         "
                // Test Our Second Iterator
                if ( it2 == _vTerms.end() )
                {
                    vTempTerms.push_back( *(--it2) );  // same as using _vTerms.back()
                }
                else
                {
                    bFound = addLikeTerms( *it, *it2, result );
                }
            }
        }
        // Now That We Have Went Through Our Container, We Need To Update It
        _vTerms.clear();
        _vTerms = vTempTerms;
        // At This point our stack variable should contain all elements from above,
        // however this temp variable can still have like terms in it.
        // ??? Were do I call the recursion and how do I define the base case
        // to stop the execution of the recursion where the base case is a
        // sorted std::vector of Term<T> objects that no two terms that are alike...
        // I do know that the recursion has to happen after the above while loop
    } // combineLikeTerms

Can someone help me find the next step? I'd be happy to hear about any bugs/efficiency issues in the code shown. I love c++

like image 409
Francis Cugler Avatar asked Oct 07 '22 06:10

Francis Cugler


1 Answers

Here's my take on it in modern C++.

Note the extra optimization of dropping terms with an effective coefficient of zero

Self contained sample: http://liveworkspace.org/code/ee68769826a80d4c7dc314e9b792052b

Update: posted a c++03 version of this http://ideone.com/aHuB8

#include <algorithm>
#include <vector>
#include <functional>
#include <iostream>

template <typename T>
struct Term
{
    T coeff;
    int exponent;
};

template <typename T>
struct Poly
{
    typedef Term<T> term_t;
    std::vector<term_t> _terms;

    Poly(std::vector<term_t> terms) : _terms(terms) { }

    void combineLikeTerms()
    {
        if (_terms.empty())
            return;

        std::vector<term_t> result;

        std::sort(_terms.begin(), _terms.end(), 
                [] (term_t const& a, term_t const& b) { return a.exponent > b.exponent; });

        term_t accum = { T(), 0 };

        for(auto curr=_terms.begin(); curr!=_terms.end(); ++curr)
        {
            if (curr->exponent == accum.exponent)
                accum.coeff += curr->coeff;
            else
            {
                if (accum.coeff != 0)
                    result.push_back(accum);
                accum = *curr;
            }
        }        
        if (accum.coeff != 0)
            result.push_back(accum);

        std::swap(_terms, result); // only update if no exception
    }
};

int main()
{
    Poly<int> demo({ { 4, 1 }, { 6, 7 }, {-3, 1 }, { 5, 5 } });

    demo.combineLikeTerms();

    for (auto it = demo._terms.begin(); it!= demo._terms.end(); ++it)
        std::cout << (it->coeff>0? " +" : " ") << it->coeff << "x^" << it->exponent;

    std::cout << "\n";
}
like image 159
sehe Avatar answered Oct 13 '22 11:10

sehe