//Devin Scheu CS1A Chapter 9, P. 538, #8
//
/**************************************************************
*
* DETERMINE MODE OF INTEGER ARRAY
* ____________________________________________________________
* This program finds the mode of a set of integer values
* in an array, which is the value occurring most frequently.
* ____________________________________________________________
* INPUT
* arraySize : The number of elements in the array
* values : The array of integers
*
* OUTPUT
* modeValue : The mode of the array or -1 if no mode exists
*
**************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
// Function to find mode using pointer notation
int findMode(int* arr, int size) {
if (size <= 0) return -1;
int* count = new int[1000](); // Assume max value is 999, initialize to 0
int maxCount = 0; // Track the highest frequency
int modeValue = -1; // Track the mode value
// Count frequency of each value and find the mode
for (int* ptr = arr; ptr < arr + size; ptr++) {
count[*ptr]++;
if (count[*ptr] > maxCount) {
maxCount = count[*ptr];
modeValue = *ptr; // Set mode to the first value with the new max count
}
}
// Check if a mode exists (more than one occurrence)
if (maxCount <= 1) {
delete[] count;
return -1;
}
// Count unique values with max count using a flag array
bool* seen = new bool[1000](); // Flag to mark seen values with max count
for (int i = 0; i < 1000; i++) seen[i] = false;
int uniqueMaxCount = 0;
for (int* ptr = arr; ptr < arr + size; ptr++) {
if (count[*ptr] == maxCount && !seen[*ptr]) {
uniqueMaxCount++;
seen[*ptr] = true;
if (uniqueMaxCount > 1) {
delete[] count;
delete[] seen;
return -1; // Multiple unique modes, no single mode
}
}
}
delete[] count;
delete[] seen;
return modeValue;
}
int main () {
//Variable Declarations
int arraySize; //INPUT - The number of elements in the array
int* values; //INPUT - The array of integers
int modeValue; //OUTPUT - The mode of the array or -1 if no mode exists
//Prompt for Input
cout << "Enter the number of elements: ";
cin >> arraySize;
cout << arraySize << endl;
//Allocate dynamic array
values = new int[arraySize];
//Input Values
for (int i = 0; i < arraySize; i++) {
cout << "Enter value " << (i + 1) << ": ";
cin >> *(values + i);
while (*(values + i) < 0) {
cout << "\nError: Please enter a non-negative value: ";
cin >> *(values + i);
}
cout << *(values + i) << endl;
}
//Calculate Mode
modeValue = findMode(values, arraySize);
//Separator and Output Section
cout << "-------------------------------------------------------" << endl;
cout << "OUTPUT:" << endl;
//Output Result
if (modeValue == -1) {
cout << left << setw(25) << "Mode:" << right << setw(15) << "No mode (-1)" << endl;
} else {
cout << left << setw(25) << "Mode:" << right << setw(15) << modeValue << endl;
}
//Clean up memory
delete[] values;
} //end of main()