i did exactly what the pseudo code told me in the book introduction to algorithms and it didn't work
there are two parts that i dont really understand
1-how do u make a recursive function that is a void i mean shouldnt a recursive function always return the last step then what is before it .. it's a void so how would it preform the task
2-merg_sor() was called twice in one function .. do u call that nested recursion ?or what ?? .. and how does it affect the merg function
#include <iostream>
#include <vector>
using namespace std;
void Merg(vector<int> Arr,int start,int middle,int end)
{
std::vector<int> left;
std::vector<int> right;
for(int i =start;i<(end-start);i++)
{
if (i <middle)
{
right.push_back(Arr.at(i));
}
else
{
left.push_back(Arr.at(i));
}
}
int j=0;
int k=0;
for(int i =start;i<(end-start);i++)
{
if(right.at(j)<=Arr.at(i))
{
Arr.at(i)=right.at(j);
j++;
}
else
{
Arr.at(i)=left.at(k);
k++;
}
}
}
void Merg_sort(vector<int> Arr,int start,int end)
{
if (start <end)
{
int middle = (start+end)/2;
Merg_sort(Arr,start,middle);
Merg_sort(Arr,middle+1,end);
Merg(Arr,start,middle,end);
}
}
int main()
{
vector<int> x;
for (int i =0;i<8;i++){x.push_back(i);}
x.at(2)=8;
Merg_sort(x,0,7);
}
1-how do u make a recursive function that is a void i mean shouldnt a recursive function always return the last step then what is before it .. it's a void so how would it preform the task
A function can have side effects. It means, that a function can modify the state of the program. A void function always works by side effects. A void function that doesn't have side effects is completely useless. Whether the function is recursive makes no difference to this question.
2-merg_sor() was called twice in one function .. do u call that nested recursion ?or what ??
I'm not sure if it is commonly used term, but I would describe it as multi-branched recursion.
2 .. and how does it affect the merg function
It doesn't, because it has no side effects.
i did exactly what the pseudo code told me
Perhaps you didn't interpret the pseudo code correctly. Perhaps the arguments are implicitly references in the pseudo-language that you're reading such as they are in languages like python.
Related
I have a problem with the initialization with various parameters in my function.
It works if I have created an array int params [] = {...}. However, it doesn't work if I want to write the parameters directly into the function.
declaration (in the .h)
void phase_an(int led[]);
in the .cpp
void RS_Schaltung::phase_an(int led[])
{
for (size_t i = 0; i < LEN(led); i++) {
digitalWrite(led[i], HIGH);
}
}
if I try this way, it won't work. I would like it to be like that. But I couldn't find anything about it on the internet. ...:
in the Arduino sketch:
RS.phase_an(RS.ampelRot, RS.ampelGelb, ..... ); <--- is there a way to do it like that?
what amazes me is that it works this way:
int p_an [5] = {RS.ampelRot, RS.ampelGelb, RS.ampelGruen, RS.rot, RS.gelb};
...................
RS.phase_an (p_an);
does anyone have a suggestion?
There are several ways of making a function accepting a variable number of arguments here.
However, in your current code there is a problem: when you pass a native array of unknown size as argument of a function (e.g. void f(int a[])), the argument will be managed a pointer to an array, and there is no way inside this function to know the real length of that array. I don't know how LEN() is defined, but chances are high that it doesn't works well in your code.
A safer and more practical alternative is to use a vector<int> instead:
#include <iostream>
#include <vector>
using namespace std;
void f(const vector<int>& a){
for (int i=0; i<a.size(); i++) {
cout<<a[i]<<" ";
}
cout<<endl;
}
int main() {
vector<int> test={1,2,3,4};
f(test);
f({1,2,3,4});
return 0;
}
In this case, you can pass your multiple values between bracket in the function call (e.g. ({RS.ampelRot, RS.ampelGelb, RS.ampelGruen, RS.rot, RS.gelb})and C++ will automatically convert it to a vector.
I was trying to write code for vertical order traversal of a tree and my code prints the result on code::blocks however it is not printing the result when the same thing is run in the geekforgeeks online ide. Why is it doing this?
void getvert(Node* root,int hd,map<int,vector<int>>m){
if(root==NULL)return;
m[hd].push_back(root->data);
getvert(root->left,hd-1,m);
getvert(root->right,hd+1,m);
}
void verticalOrder(Node *root)
{
map<int,vector<int>>m;
int hd=0;
getvert(root,hd,m);
auto it=m.begin();
for(;it!=m.end();it++)
{
for (int i=0; i<it->second.size(); ++i)
cout<<it->second[i];
cout<<endl;
}
}
The function getvert accepts the last argument, m, as a value. Changes made to it in the function are made to a local copy of the object. Hence, you don't see any changes in verticalOrder.
Change getvert so that it accepts m as a reference.
void getvert(Node* root,int hd, map<int,vector<int>>& m) // Need reference argument
{
...
}
My tentative answer is no, as observed by the following test code:
#include <functional>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void TestFunc (void);
int TestFuncHelper (vector<int>&, int, int);
int main (int argc, char* argv[]) {
TestFunc ();
return 0;
} // End main ()
void TestFunc (void) {
// Recursive lambda
function<int (vector<int>&, int, int)> r = [&] (vector<int>& v_, int d_, int a_) {
if (d_ == v_.size ()) return a_;
else return r (v_, d_ + 1, a_ + v_.at (d_));
};
int UpperLimit = 100000; // Change this value to possibly observe different behaviour
vector<int> v;
for (auto i = 1; i <= UpperLimit; i++) v.push_back (i);
// cout << TestFuncHelper (v, 0, 0) << endl; // Uncomment this, and the programme works
// cout << r (v, 0, 0) << endl; // Uncomment this, and we have this web site
} // End Test ()
int TestFuncHelper (vector<int>& v_, int d_, int a_) {
if (d_ == v_.size ()) return a_;
else return TestFuncHelper (v_, d_ + 1, a_ + v_.at (d_));
} // End TestHelper ()
Is there a way to force the compiler to optimise recursive tail calls in lambdas?
Thanks in advance for your help.
EDIT
I just wanted to clarify that I meant to ask if C++11 optimizes recursive tail calls in lambdas. I am using Visual Studio 2012, but I could switch environments if it is absolutely known that GCC does the desired optimization.
You are not actually doing a tail-call in the "lambda" code, atleast not directly. std::function is a polymorphic function wrapper, meaning it can store any kind of callable entity. A lambda in C++ has a unique, unnamed class type and is not a std::function object, they can just be stored in them.
Since std::function uses type-erasure, it has to jump through several hoops to call the thing that was originally passed to it. These hoops are commenly done with either virtual functions or function-pointers to function template specializations and void*.
The sole nature of indirection makes it very hard for optimizers to see through them. In the same vein, it's very hard for a compiler to see through std::function and decide whether you have a tail-recursive call.
Another problem is that r may be changed from within r or concurrently, since it's a simple variable, and suddenly you don't have a recursive call anymore! With function identifiers, that's just not possible, they can't change meanings mid-way.
I just wanted to clarify that I meant to ask if C++11 optimizes recursive tail calls in lambdas.
The C++11 standard describes how a working program on an abstract machine behaves, not how the compiler optimizes stuff. In fact, the compiler is only allowed to optimize things if it doesn't change the observable behaviour of the program (with copy-elision/(N)RVO being the exception).
Following code for max-heap implementation
#include<iostream>
#include<math.h>
using namespace std;
#define maxn 1000
int x[maxn];
int parent(int i){
return int(i/2);
}
int left(int i){
return 2*i;
}
int right(int i){
return 2*i+1;
}
void max_heap(int x[],int i,int size){
int largest;
int l=left(i);
int r=right(i);
if (l<=size && x[l]>x[i]){
largest=l;
}
else
{
largest=i;
}
if (r<=size && x[r]>x[largest]){
largest=r;
}
if (largest!=i) { int s=x[i];x[i]=x[largest];x[largest]=s;}
max_heap(x,largest,size);
}
int main(){
x[1]=16;
x[2]=4;
x[3]=10;
x[4]=14;
x[5]=7;
x[6]=9;
x[7]=3;
x[8]=2;
x[9]=8;
x[10]=1;
int size=10;
max_heap(x,2,size);
for (int i=1;i<=10;i++)
cout<<x[i]<<" ";
return 0;
}
When I run it, it writes such kind of warning:
1>c:\users\datuashvili\documents\visual studio 2010\projects\heap_property\heap_property\heap_property.cpp(36): warning C4717: 'max_heap' : recursive on all control paths, function will cause runtime stack overflow
Please tell me what is wrong?
The message tells you exactly what's wrong. You haven't implemented any checks to stop the recursion. One smart compiler.
max_heap function doesn't have base case, i.e., a return statement. You are just recursively calling the function but never saying when to break another successive call to the max_heap.
Also, in your example you are just calling the function with out satisfying any condition. Usually recursion is done or not done when a case is satisfied.
please tell me what is wrong?
Another problem that I see is that the size of your array x is 10. But the indices that you are using to set values are 1-10.
Put
max_heap(x,largest,size);
inside last check, like this:
if (largest!=i)
{
int s=x[i];
x[i]=x[largest];
x[largest]=s;
max_heap(x,largest,size);
}
and you're done!
There are many other problems with your code, but to answer your specific question, above change would do!
I have two questions, the second being optional.
First, in the program below (a prototype of a simple card program), I am getting the following error:
(29): error C2660: 'shuffle' : function does not take 1 arguments
with the following code:
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <deque>
#include <algorithm>
using namespace std;
deque<int> cardDeck (51);
void flip(); //Prototype flip()
void shuffle(); //Prototype shuffle()
int _tmain(int argc, _TCHAR* argv[])
{
ostream& operator<<(ostream& os, deque<int> dq); //overload << operator to accept deque
//arguments
for (int a=52; a>0; a--) { //initialize the 52 cards in a deck
cardDeck.push_front(a);
}
flip(); //prompt my input to check data
return 0;
}
void flip() { //flip over card in specified location in the deck
int input;
cin >> input;
cout<<cardDeck[input]<<endl;
shuffle(cardDeck);
flip();
}
void shuffle(deque<int> dq) { //use Fisher-Yates algorithm to efficiently and accurately
//randomize card order
for(int i=dq.size()-1; i>-1; i--) {
int j = rand() % (i + 1);
if(i != j) {
swap(dq[j], dq[i]);
}
}
}
Why do I receive this error? (I have looked around and attempted to solve it myself)
Secondly, I'm not certain if I'm doing the fisher-yates algorithm properly because c++ documentation isn't easy to find on it (for the version that utilizes swap();) (Brownie points for answering this or pointing out any horribly awful coding practices, not including the lack of classes)
Thanks in advance!
The reason you get that error is because you declare shuffle as a function not taking any arguments.
void shuffle();
Another note is that you probably want to take a reference to the deque in that function, otherwise you'll shuffle a local copy and won't have the desired side effect.
You probably want it to lok like this:
void shuffle(deque<int>& dq);
Also, you might want to use iter_swap instead of swap to swap the elements. In a dequeue it probably won't make a difference, but for list or map it would.
I think you forgot to put the argument in your function declaration
void shuffle();
should be
void shuffle(deque<int> dq);
I think that the problem is that at the top of your program you've prototyped `shuffle as
void shuffle();
Notice that this takes no arguments. Because C++ uses a one-pass compiler, at the point that you call shuffle, this is the only declaration of shuffle available because the compiler hasn't seen the implementation later on. Consequently, it gives you the above error, because it thinks you are calling a zero-argument function with one argument.
To fix this, update the prototype so that it matches the function you've actually defined.
Hope this helps!