Question

Using ONLY the following header functions: #include "cmpt_error.h" #include <iostream> #include <string> #include <vector> #include <cassert>...

Using ONLY the following header functions:

#include "cmpt_error.h"
#include <iostream>
#include <string>
#include <vector>
#include <cassert>
using namespace std;

Create a C++ function that satisfies the condition using recursion, NO WHILE OR FOR LOOPS.

Pre-condition:
     a.size() == b.size(), and a.size() > 0
Post-condition:
     Returns a vector equal to {min(a[0],b[0]), min(a[1],b[1]),
     min(a[2],b[2]), ..., min(a[n],b[n])}, where n == a.size().

For example, min_vec({3, 4, 1}, {2, 5, 2}) returns the new vector {2, 4, 1}.

These are the function headers:
vector<int> min_vec(const vector<int>& a, const vector<int>& b);
void min_vec_test();
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code:

//helper function

void help_min_vec(const vector<int>& a, const vector<int>& b,vector <int>& c,int idx)
{
   if(idx>=a.size()) return;
   c.push_back(min(a[idx],b[idx]));
   return help_min_vec(a,b,c,idx+1);
}
vector<int> min_vec(const vector<int>& a, const vector<int>& b)
{
   vector <int> c;
   help_min_vec(a,b,c,0);
   return c;
}
void min_vec_test(){
   cout<<"Testing min_vec... ";
   assert((min_vec({1},{2})== vector <int> {1}));
   assert((min_vec({1,10},{5,2}) == vector <int> {1,2} ));
   assert((min_vec({3,4,1},{2,5,2})== vector <int> {2,4,1}));
   cout<<"all min_vec tests passed!\n";
}

===========

I have tested it using :

Output:

=========

Since we are creating vectors using extended intializers use c++11 or above to run the code.

min_vec() functions calls another helper function help_min_vec() which takes four arguments. The first three are vector and last one is int. The purpose of variable idx is to maintain check on which element we have reached and push the current minimum value for that index. After that it is incremented and recursive call is made thus avoiding the use of the loops. The testing function uses assert() to check the min_vec() function returned output.

Please comment if you don't understand any part of code.

Add a comment
Know the answer?
Add Answer to:
Using ONLY the following header functions: #include "cmpt_error.h" #include <iostream> #include <string> #include <vector> #include <cassert>...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT