In racket, implement a tail-recursive function called sum-pairs that creates a new list by adding the elements of an input list in pairs. That is the first element of the resulting list is the sum of the first two elements of the input, the second element of the resulting list is the sum of the 3rd and 4th elements of the input, and so on. If there is an odd number of elements, then the last element remains unchanged. As an example, (sum-pairs ’(1 2 3 4 5)) will result in ’(3 7 5). It may be helpful to create helper functions.
RACKET!!!
>Answer
>Given
#include <iostream>
#include <vector>
#define N 100
using namespace std;
vector<int> tail_recursive(vector<int> vec){
int l= vec.size();
vector<int> v2;
for(int i=0;i< l - 1;i+=2){
v2.push_back(vec[i] + vec[i+1]);
}
if(l%2 !=0) v2.push_back(vec[l - 1]);
return v2;
}
int main()
{
vector<int> vec, vec2;
for(int i=0;i<5;i++){
vec.push_back(i+1);
}
cout<<"Initial Value: ";
for(int i=0;i<vec.size();i++){
cout<<vec[i]<<" ";
}
cout<<endl;
vec2 = tail_recursive(vec);
int l= vec2.size();
cout<<"Tail Recursive Value: ";
for(int i=0;i<l;i++){
cout<<vec2[i]<<" ";
}
cout<<endl;
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.