#include <cassert> #include <vector> using namespace std; //REQUIRES: v is not e
ID: 3744847 • Letter: #
Question
#include <cassert>
#include <vector>
using namespace std;
//REQUIRES: v is not empty
//EFFECTS: returns a summary of the dataset as (value, frequency) pairs.
//In the returned vector-of-vectors, the inner vector is a (value, frequency) pair. The outer vector contains many of these pairs.
// {
// {1, 2},
// {2, 3},
// {17, 1}
// }
// This means that the value 1 occurred twice, the value 2 occurred 3 times, and the value 17 occurred once
// Complete the function below
std::vector<std::vector<double> > summarize(std::vector<double> v);
//REQUIRES: v is not empty
//EFFECTS: returns the mode of the numbers in v
// http://en.wikipedia.org/wiki/Mode_(statistics)
// Example: mode({1,2,3}) = 1
// Example: mode({1,1,2,2}) = 1
// Example: mode({2,2,1,1}) = 1
// Example: mode({1,2,1,2}) = 1
// Example: mode({1,2,1,2,2}) = 2
// In the event of a tie, return the smallest value (as in the
// above examples)
//HINT 2: use a nested loop
//HINT 3: use a variable to remember the most frequent number seen so far
// Complete the function below
double mode(std::vector<double> v);
Explanation / Answer
Executable code -:
#include <bits/stdc++.h>
using namespace std;
double mode(vector<double> v,int n)
{
int count[n]={0};
sort(v.begin(),v.end());
for (int i = 0; i < n; i++) //nested loop
{
for(int z=i+1;z<n;z++)
{
if(v[i]==v[z])
{
count[i]++;
}
}
}
int maxCount = INT_MIN; // variable that contain most frequent number
int modeValue = 0;
for (int i = 0; i < n; i++)
{
if (count[i] > maxCount)
{
maxCount = count[i];
modeValue = v[i];
}
}
return modeValue;
}
int main() {
vector <double> v1={1,2,3};
vector <double> v2={1,2,1,2};
vector <double> v3={1,2,1,2,2};
cout <<"Mode for first vector "<< mode(v1,v1.size()) << endl;
cout <<"Mode for second vector " << mode(v2,v2.size())<<endl;
cout << "Mode for third vector "<<mode(v3,v3.size())<<endl;
return 0;
}
Explanation :-
1. maxCount is a variable that contains the frequency of the most frequent number seen so far.
2. modeValue is a variable that contains the most frequent number seen so far.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.