C++ Class Averages

From Genome Analysis Wiki
Revision as of 12:27, 2 August 2010 by Mktrost (talk | contribs) (Created page with '<source lang="cpp"> // Static method that returns the mean, meadian, and mode for this dataset. void Average::calculateAverages(double& mean, doub…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search
// Static method that returns the mean, meadian, and mode for this dataset.
void Average::calculateAverages(double& mean,
                                double& median,
                                std::vector<int>& modes)
{
    // Track the number of entries that have been passed so far.
    // This is for determing the median.
    int numSeen = 0;
    int dataSetSize = myDataSet.size();
    bool isOdd = (NumDataValues() % 2);
    int midPoint = NumDataValues() / 2;

    median = -1;
    int average = 0;
    
    for(int i = 0; i < dataSetSize; i++)
    {
        if(median == -1)
        {
            // Still haven't calculated median, so keep checking it.
            numSeen += myDataSet[i];
            if(numSeen >= midPoint)
            {
                // Have reached the midpoint.
                // If the length is odd, just return this value.
                if(isOdd)
                {
                    median = i;
                }
                else
                {
                    // The length is even.  So need to take the two midpoints
                    // and average them.  midPoint is set to the first midpoint
                    // also, the next one needs to be averaged.
                    // the previous value and average them.
                    if(numSeen == midPoint)
                    {
                        if(average == 0)
                        {
                            average = i;
                        }
                    }
                    else
                    {
                        if(average == 0)
                        {
                            median = i;
                        }
                        else
                        {
                            median = (average + i)/2.0;
                        }
                    }
                }
            }
        }

        // Determine if this position is part of the mode.
        if(myDataSet[i] == myMaxCount)
        {
            modes.push_back(i);
        }
    }
}