How do you calculate mode from an array of integers?

Showing Answers 1 - 3 of 3 Answers

sukhvir

  • Sep 26th, 2007
 

If array in ascending order use binary search otherwise use sequential search

  Was this answer useful?  Yes

OSaienni

  • Sep 11th, 2008
 

Below is an example program I wrote to find mode average. Mode average is the most frequently occuring number in a set.
I haven't handle the case when there are 2 or more values with the same count.

#include <iostream>

#include <set>

int main()

{

typedef std::multiset<int> int_multiset;

int_multiset mySet;

//populate collection

mySet.insert(10);

mySet.insert(1);

mySet.insert(23);

mySet.insert(23);

mySet.insert(3);

mySet.insert(41);

mySet.insert(2);

mySet.insert(10);

mySet.insert(23);

mySet.insert(54);

mySet.insert(23);

mySet.insert(10);

mySet.insert(12);

mySet.insert(43);

mySet.insert(23);


//find mode average, mode average is most frequently appearing number.

int nModeValue = 0;

int nModeCount = 0;

//get beginning iterator

int_multiset::iterator iter = mySet.begin();

//NOTE: I DON'T HANDLE CASE WHERE MODE IS NOT UNIQUE

while(iter != mySet.end()) {

//get current value and count

const int nCurrent = *iter;

const int cCurrent = mySet.count(nCurrent);

if(cCurrent > nModeCount) {

nModeValue = nCurrent;

nModeCount = cCurrent;

}

//move iterator by number of count

for(int nMove = 0; nMove < cCurrent; ++nMove, ++iter);

}

std::cout <<
"Mode Average Is : " << nModeValue << std::endl;

return 0;

}

  Was this answer useful?  Yes

OSaienni

  • Sep 11th, 2008
 

Same as above except using arrays.

#include <iostream>

#include <algorithm>

int main()

{

int arrNums[] = {1,2,4,5,1,3,4,2,3,4};

//find mode average, mode average is most frequently appearing number.

int nModeValue = 0;

int nModeCount = 0;

const int nArrayLen = sizeof(arrNums) / sizeof(arrNums[0]);

std::sort(&arrNums[0], &arrNums[nArrayLen]);


//NOTE: I DON'T HANDLE CASE WHERE MODE IS NOT UNIQUE

int nIter = 0;while(nIter != nArrayLen)

{

// //get current value and count

const int cCurrent = std::count(&arrNums[nIter], &arrNums[nArrayLen], arrNums[nIter]);if(cCurrent > nModeCount) {

nModeValue = arrNums[nIter];

nModeCount = cCurrent;

}

nIter += cCurrent;

}

std::cout <<
"Mode Average Is : " << nModeValue << std::endl;

return 0;

}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions