Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write each of the following functions in Java or C++. You must use the API of a

ID: 3583153 • Letter: W

Question

Write each of the following functions in Java or C++. You must use the API of a list class in the library. take(1 st, n) This function returns the n-element prefix of 1st if n is less than the size of 1st; otherwise, it returns let itself. For example, if 1st is ['a', 'b', 'c', 'd'] and n is 3, then the return list is ['a', 'b', 'c']. sublists(1st, n). This function returns all n-element sublists of 1st. For example, if let is ['a', 'b', 'c'] and n is 2, then the returned list is: [['a', 'b'], ['b', 'c'], ['c', 'd']].

Explanation / Answer

Code:

#include<iostream>
#include<list>
#include<iterator>
using namespace std;

template<typename T>
void take(list<T> &lst,int n)
{
int s=lst.size();
if(n>s)
   n=s;

typename list<T>::iterator itr=lst.begin();

for(int i=0;i<n;i++,itr++)
   cout<<*itr<<" ";

cout<<endl;
}

template <typename T>
void sublists(list<T> &lst, int n)
{
int s=lst.size();
if(n>s)
   n=s;

typename list<T>::iterator itr2;

for(typename list<T>::iterator itr=lst.begin();itr!=lst.end();)
{
   itr2=itr;


   for(int i=0;i<n;i++,itr2++)
   cout<<*itr2<<" ";
   cout<<endl;
   if(itr2==lst.end())
   itr=lst.end();
    else
   itr++;
}
}

int main(void)
{

list<int> myList;

for(int i=0;i<10;i++)
   myList.push_back(i);

take(myList,4);
sublists(myList,3);

return 0;
}

Output:

1 2 3 4 //Output from take() function

//Output from sublists function

1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9
8 9 10

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote