Write a function that accepts arguments as the following: - an array of integers
ID: 3561175 • Letter: W
Question
Write a function that accepts arguments as the following:
- an array of integers
- an integer that indicates the number of elements in the array.
the function should determine the mode of the array. that is, it should determine which value in the array occurs most often. The mode is the value that function should return. If the array has no mode (none of the values occur more than once), the function should return -1. (Assume the array will always contain non-negative values.) Demonstrate by using pointer notation instead of array notation.
Explanation / Answer
#include<iostream> //for cout
#include<vector> //for vector used
#include<algorithm> //for sorting
using namespace std;
/*
*Algorithm
*1) sort the array
*2) Count the number of times each number is repeated.
*3) Identify the value that occur most often
*/
int getMode(int* arr, int size){
int mode = -1; //mode of part of sorted array that is processed, if exist
int modeCount=1; //count of the mode of part of sorted array that is processed
int count; //number of times any number is present in sorted array
/*
*make a vector of given array so that we can sort the elements using pre-defined sort function
*/
vector<int> arrVector (arr, arr+size);
sort (arrVector.begin(), arrVector.end());
count = 1; //any number is present at least once
for(int index = 1; index<size; index++){
if(arrVector[index-1]==arrVector[index]){
count++; //number is same as previous, increment its count
}
else{ //a new number has came up
if(count>modeCount){ //if the count of previous number is greater than count of mode in part of array that is already seen
modeCount = count; //then this is the mode
mode = arrVector[index-1];
}
count = 1; //count of new number is 1 as we have seen it only once
}
}
return mode; //if all number do not repeat, execution do not enter else part and mode is not update
}
/*
* Main function to check the written function
*/
int main(){
int arr1[] = {1,2,3,4,1,2,6,7,4,3,5,4,9,10};
cout<<getMode(arr1,14)<<endl;
int arr2[] = {1,2,3,4};
cout<<getMode(arr2,4)<<endl;
}
Output:
4
-1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.