HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Calculating the mode of a set of ints

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
themodecalculatingsetints

Problem

I have to read in a file full of ints, print them in reverse order, and then calculate the median and the mode of the set.

At first I struggled with figure out a way to calculate the mode. It seemed so simple but I just couldn't translate the steps into code. I did come up with a solution and it works but because of my struggle at first I just wanted to get some feedback on if this was a good method or if there's better ways to do it.

```
#include //IO to the screen
#include //File IO
#include //String manipulation

using namespace std;

/CONSTANTS/
const int MAX_ELEMENTS = 100;
const string FILENAME = "data.dat";

/TYPEDEFS/
typedef int IntArr[MAX_ELEMENTS]; //data type for an integer array of 100 elements.

/PROTOTYPES/
void Print(const IntArr& outArr, int numFilled); //Prints the array in reverse order.
void Sort(IntArr& outArr, int numFilled);
int CalcMode(const IntArr& numArr, int numFilled);

void main()
{
/VARIABLES/
IntArr numArr; //Holds the integers read in from the file.

ifstream din;
din.open(FILENAME.c_str());

//The file exists.
if(!din)
{
cout > num;
//While the last read was successfull
while(din)
{
//Place the num into the array, increment the index counter, and read the next int.
numArr[ind] = num;

ind++;

din >> num;
} //End while loop

Print(numArr, ind);

Sort(numArr, ind);

int median = (ind - 1) / 2;

cout = 0; i--)
{
cout outArr[i+1])
{
int temp = outArr[i];
outArr[i] = outArr[i+1];
outArr[i+1] = temp;
sorted = false;
}//End If
}//End For
}//End While
}//End Sort()

//Pre: The array passed in should already be sorted.
//Post: Returns the number that occurs the most.
//Purpose: Determine which number occurs

Solution

If you have a sorted array and want to determine the most frequently-occurring value, use the fact that all repetitions of the same value will be adjacent.

Now you know what you're aiming for, can you write it yourself, or do you want to see the code?

Hint: you don't need an associative store of counters off to the side, only:

  • the most-occurring value so far (longest run seen)



  • the number of times it occurred (run length)



  • the value in the current run



  • the length of the current run so far



  • a working index to iterate over the input array



It's a 1-pass algorithm with linear time and constant space overhead. It's actually related to run-length encoding, if that helps.

Context

StackExchange Code Review Q#15397, answer score: 5

Revisions (0)

No revisions yet.