Skip to main content
4 of 6
deleted 3 characters in body; edited title
Jamal
  • 34.9k
  • 13
  • 133
  • 237

Mean, Median and Mode

I would like some help condensing this code down to size. I am trying to utilize Qt's container classes as efficiently as possible. I do not believe this code reflects my objective.

#include <QCoreApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

QVector<int> vect;

vect.append(0);
vect.append(0);
vect.append(0);
vect.append(0);
vect.append(1);
vect.append(1);
vect.append(2);
vect.append(1);

QVectorIterator<int> ivect(vect);

double median = 0;
if(vect.count() % 2 == 0){

    median =
    static_cast<double>((vect[vect.count() / 2 - 1] + vect[vect.count() / 2])) / 2;
}
else{

    median = vect[vect.count() / 2];
}

int sum = 0;
while(ivect.hasNext()){

    sum += ivect.next();
}

double mean = static_cast<double>(sum) / vect.count();

QSet<int> set;

ivect.toFront();
while(ivect.hasNext())
{
    set << ivect.next();
}

QMap<int, int> map;

QSetIterator<int> iset(set);

ivect.toFront();
while(iset.hasNext())
{
    int count = 0;
    while(ivect.hasNext())
    {
        if(iset.peekNext() == ivect.next())
        {
            count++;
        }
    }
    ivect.toFront();
    map.insert(iset.next(), count);
}

QMapIterator<int, int> imap(map);

int maxValue = 0;
QString mode;
while(imap.hasNext())
{
    imap.next();
    if(imap.value() > maxValue)
    {
       maxValue = imap.value();
       mode = QString::number(imap.key());
    }
    else if(imap.value() == maxValue)
    {
        mode = "NULL";
    }
}

qDebug() << set;
qDebug() << map;
qDebug() << "Mean:" << mean;
qDebug() << "Median:" << median;
qDebug() << "Mode frequency:" << maxValue;
qDebug() << "Mode:" << mode;

return a.exec();
}