Write a C++ function: Here is the function you should implement: // // // vector
ID: 3677775 • Letter: W
Question
Write a C++ function:
Here is the function you should implement:
//
//
// vector<float> local_average(vector<string> w, int loc) { }
//
// Find the average length of the strings in the vector *w*
// over an averaging interval of *loc*, with the averaging "window"
// shifting by one each time.
//
// That is, we take the average length of *w* for the first *loc*
// strings, then the strings from 1 to *loc*,
// then the strings from 2 to *loc*+1,
// The last value in the returned vector *w*
// will be the average length of the last *loc* strings in *w*
// Example results:
//
// w loc output
// abc abd a b c 1 3 3 1 1 1
// a z w aaa 123 2 1 1 2 3
// abc abc a b c 3 2.33 1.67 1
// abc a b c abd 4 1.5 1.5
// a bcd e 2 2 2
// a b abcedae w x z 3 3 3 3 1
// a 22 333 1 2 1.5 2.5 2
Explanation / Answer
code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<float> local_average(vector<string> w, int loc) {
vector<float> result;
int i=0;
for(i=0;i+loc-1<w.size();i++) // a z w aaa 123 loc =2
{
//cout<<"enter";
float avg=0;
int j;
for(j=i;j<=i+loc-1;j++)
{
avg+=w[j].size();
}
avg=avg/loc; //finding average of the window
result.push_back(avg);
//cout<<avg;
}
return result;
}
int main()
{
vector<string> v;
v.push_back("abc");// one of the testing input
v.push_back("zbc");
v.push_back("a");
v.push_back("b");
v.push_back("c");
vector<float> res = local_average(v, 3);
for(int i=0;i<res.size();i++)
{
cout<<res[i]<<" ";
}
return 0;
}
It is working for all your give Example results:
if you have any doubt then please comment.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.