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

Here is one I am rather stumped on! The mode is the value that appears most ofte

ID: 665864 • Letter: H

Question

Here is one I am rather stumped on!

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 ints 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. Depending on your algorithm, it may be easier (though less efficient) to just sort the vector at the end before returning it. Sorting a vector is 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());".  Don't alter the original array.

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 such values.

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

Explanation / Answer

vector<int> findMode(int data[], int size)
{
   int uniqueElementArray[size]   ;
   int countArray[size];
   std:: sort(std::begin(data), std::end(data));
   int item = data[0];
   int freq = 0;int index = 0;
   for(int i=0; i< size; i++)
   {
       if(item == data[i])
       {
           freq++;  
       }
       else
       {
           uniqueElementArray[index] = data[i];
           countArray[index] = freq;
           freq = 0;
           item = data[i];              
       }
      
   }

   int max = countArray[0];
   int maxIndex = 0;
   for(int j=1; j< size; j++)
   {
       if(max < countArray[j])
       {
           maX = countArray[j];
           maxIndex = j;  
       }  
   }

   vector<int> v1;

   if(countArray[0] == 0 && maxIndex ==0)
   {
       for(int k = 0; k < size; k++)
       {
           v1.push_back(uniqueElementArray[k]);  
       }
   }
   else
   {
       v1.push_back(uniqueElementArray[maxIndex]);  
   }
  
return v1;
  
}

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