Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The mode is the value that appears most often in a set of data. Write a function

ID: 3668873 • Letter: T

Question

The mode is the value that appears most often in a set of data.  Write a function named findMode that takes as parameters an array of int and the size of the array, and returns a vector containing the mode(s). If there is just a single most frequent value, the vector will only contain that one value, but if multiple values tie for maximum frequency, the vector will need to contain all such values. This includes the case where every number in the array appears only once. Each mode should appear only once in the vector.   The values in the vector that is returned must be in ascending order.   If you need to sort a vector, it's similar to sorting an array, but specifying the beginning and end of the vector look a little bit different. If your vector is named result, then it would look like this: "std::sort(result.begin(), result.end());".

The most straightforward approach is to:

Iterate (loop) through the array to find out what the highest frequency for any value is without worrying about storing any modes.

Iterate through the array again, this time comparing the counts for each value to the highest frequency that you already found, if the count for a value is the same as the highest frequency, push that value into your results vector.

The file must be named: findMode.cpp

Map header file and pointers can't be used.

Explanation / Answer


#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <cstdlib>
#include <algorithm>

using namespace std;

// function prototypes
// Finds the mode(s) of the ints in the specified vector.
vector<int> findMode(const vector<int> &);
// Determines whether a string is a valid integer.
bool isInteger(const string &);

int main()
{
    // declare variables
    vector<int> input; // stores user input
    string buffer;     // stores unvalidated input
  
    cout << "This program finds the mode(s) of a list of integer values. "
         << "Press Enter without any value when you are done. ";
       
    do
    {
        cout << "Enter a value: ";
        getline(cin, buffer);
      
        // check if valid input
        if (isInteger(buffer))
        {
            // add to vector
            input.push_back(atoi(buffer.c_str()));
        }
        else if (!buffer.empty())
        {
            // invalid input
            cout << "Invalid integer. Try again. ";
        }
    } while (!buffer.empty());
  
    if (!input.empty()) // non-empty
    {
        // get the mode(s)
        vector<int> result = findMode(input);
      
        // display result(s)
        if (result.size() > 1)
        {
            // fencepost
            cout << " The modes are " << result[0];
            for (int i = 1; i < result.size(); i++)
            {
                if (i == result.size() - 1)
                    cout << " and " << result[i] << ". ";
                else
                    cout << ", " << result[i];
            }
        }
        else if (result.size() == 1)
        {
            cout << " The mode is " << result[0] << ". ";
        }
    }
    else              // empty
    {
        cout << " You did not enter any integers. ";
    }

    return 0;
}

/**
    bool isInteger(const string &str)
  
    Purpose:
        This function determines whether a string is a valid integer.
  
    Preconditions:
        none
  
    Postconditions:
        returns true if string only contains 0-9, false otherwise
*/
bool isInteger(const string &str)
{
    // return false if empty
    if (str.length() < 1)
        return false;
  
    // check each char
    for (int i = 0; i < str.length(); i++)
    {
        if (!isdigit(str[i]) && (i != 0 || str[i] != '-'))
            return false;
    }
  
    // no non-digits found
    return true;
}

/**
    vector<int> findMode(const vector<int> &vals)
  
    Purpose:
        This function finds the mode of the integer values in the specified
        vector. Returns multiple values if there is more than one mode.
  
    Preconditions:
        vals is initialized
  
    Postconditions:
        returns a vector containing the mode(s)
*/
vector<int> findMode(const vector<int> &vals)
{
    // create working vectors
    vector<int> sorted (vals);
    vector<int> results;
  
    // return empty vector if vals is empty
    if (vals.empty())
        return results;
  
    // sort vector into ascending order
    sort(sorted.begin(), sorted.end());
  
    // add first element to result
    results.push_back(sorted[0]);
    int prev = sorted[0];
    int highCount = 1;
    int count = 1;
  
    // check for repeats in sorted vector and keep track of highest count
    for (int i = 1; i < sorted.size(); i++)
    {
        if (sorted[i] == prev)
        { // current value same as previous
            count++;
            if (count > highCount)
            {
                // update highCount
                highCount = count;
                // clear previous results unless current value is only result
                if (results.size() > 1 || results[0] != sorted[i])
                {
                    results.clear();
                    results.push_back(sorted[i]);
                }
            }
            else if (count == highCount)
            {
                // add current value to results
                results.push_back(sorted[i]);
            }
        }
        else
        { // different value--reset count and prev variables
            count = 1;
            prev = sorted[i];
            if (count == highCount)
            {
                // add current value to results
                results.push_back(sorted[i]);
            }
        }
    }

    return results;
}


sample output

                                                                                                                                                
This program finds the mode(s) of a list of integer values.                                                                                                 
Press Enter without any value when you are done.                                                                                                            
                                                                                                                                                            
Enter a value: 10                                                                                                                                           
Enter a value: 20                                                                                                                                           
Enter a value: 30                                                                                                                                           
Enter a value: 40                                                                                                                                           
Enter a value: 50                                                                                                                                           
Enter a value:                                                                                                                                              
                                                                                                                                                            
The modes are 10, 20, 30, 40 and 50.                                                                                                                        

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote