I am facing following problem with recursion. It is simple backtracking to print all the permutation, but I want to stop it from the base condition. For example, 4 character string will show 4!=24 strings. But I want to show first 20 strings only.
k is used for the purpose, k=20,for the example. Suppose, str="ABCD". I want to stop recursion after exactly 20 operations. How can I do this? I have tried to solve it in this way.
void permutation(string str,int l,int r,int k)
{
k--;
if(l==r||k==0) {
cout<<str<<endl;
return;
}
else{
for(int i=l;i<r;i++)
{
swap(str[l],str[i]);
permutation(str,l+1,r,k);
swap(str[l],str[i]);
}
}
}
If you want to use the unfortunately named k as a counter like that, it will count recursion levels, not results. If you want to count results, you need to store the counter outside of your function, either as a static or as a reference you pass to your function, and increment it every time you output a result.
You have two solutions to count the number of times results are printed:
1- Defining k as a global variable outside the function.
2- Defining k as a static variable: static int k = 0;.
Note that in both these solutions, k should be eliminated from the parameter list of the function.
I would also suggest choosing meaningful names for your variables. This way, it will be easier to understand and follow the code both for you and someone else who is going to help.
Related
I am trying to write a code that uses 2 recursive functions; 'I' and 'U' and one non-recursive function 'f'. What I am tring to achive is to run the recursive function I "steps1" many times and then stop at this level to then run the recursive funtion U "steps2" many times.
After that, finally run the non-recursive function f at the level where function U's iteration ends.
For example:
Let steps1=1 and steps2=1 then,
I will iterate function 'I', 1-time(steps1) and get:
I(n)= 3*I(n/2)+7*n-3
then, I will iterate funtion U, 1-time(steps2) for n/2 value. And then, insert it instead of I(n/2), thus I will calculate:
I(n)= 3*[U(n/2)]+7*n-3= 3*[2*U(n/6)+2*(n/2)-9] = 3*2*U(n/6)+3*2*(n/2)-3*9
now insert last function f(n/6), into this equation:
3*2*U(n/6)+3*2*(n/2)-3*9=3*2*f(n/6)+3*2*(n/2)-3*9
since f is non-recursive, this will give me the result.
When I run my code I get, "unhandeled exception" error. Can someone help me find the reason for this error? Is my code wrong at somewhere? Can someone help me fix this please? I am not sure if my code does exactly what I want to do, as well?
#include<stdlib.h>
#include<bits/stdc++.h>
using namespace std;
int f(int n)
{
return (n-1)*(n-1);
}
/* step2 many iteration of the function U and then function f */
int U(int n , int steps2, int counter2=0)
{
if(counter2==steps2){
return f(n);
}
return 2*U(n/3, steps2, counter2+1)+2*n-9;
}
/* step1 many iteration of the function I and then function U*/
int I(int n , int steps1,int steps2, int counter1=0, int counter2=0)
{
if(counter1==steps1){
return U(n,steps2,counter2);
}
return 3*I(n/2, steps1, counter1+1)+7*n-3;
}
int main(){
int n, steps1,steps2;
cout<< " Enter 'n' value which is divisable by both 2 and 3"<<"\n";
cin>>n;
cout<< " Enter iteration count for I"<<"\n";
cin>>steps1;
cout<< " Enter iteration count for U"<<"\n";
cin>>steps2;
cout<< " result:" << I(n,steps1,steps2)<<"\n";
getchar();
return 0;
}
I compiled and ran your program and it looks like you're getting a stack overflow. The recursion for function I isn't correct. Namely your base case will never be reached. In each location that I is called you only pass 3 parameters, thus counter1 is always going to have a value of 0, the default value. Also, I is always called such that steps1 is always going to have the same value (from the user's input). So if(counter1==steps1){ will never be true.
Some advice for future problems, when troubleshooting a problem like this, one of the easiest things you can do is to add a cout to the beginning of each function. Print the function name and the parameter values. Another option is to hook up a debugger and set some break points. Learning how to use a debugger with C++ will come in very, very handy.
So for the past 4 months i've been learning C++ and I made lots of progress, actually getting very close to learning graphs soon.
There's just one thing that I still have problems and and I just don't get it, and that is the variables on a function.
Basically I do not know what kind of variables to put inside the () of a function in the beginning, and what variables I need to put after.
I know it depends on the exercise, so i'll try to give an example.
so I want to calculate the sum of a and b in a function.
int calculateSum(int a, int b){
int sum;
}
so why do I put under the function and not inside the parenthesis?
why can't it just be like:
int calculateSum(int a, int b, int sum){
//code
}
Variables inside the () are the parameters of your function. That is, the inputs it expects when it is called from other code. The variables inside the {} are for use exclusively inside your function.
Your first example makes sense - you'd use it something like this:
int answer = calculateSum(1, 2);
What would you pass as an argument for the sum parameter in your second example? It's sort of a meaningless request - the caller of your function wants to get the sum back from your routine.
In reality everything depends on the definition of the function. For example we can define a function as follows.
int CalculateSum (int a, int b, int sum);
This function necessarily receives three integers a, b and sum.
The body of the function can be defined
for example like this:
int CalculateSum (int a, int b, int sum) {
sum = a + b;
return sum;
}
We can also define the function as well.
int CalculateSum (int a, int b);
This function receives two integers a and b.
the body of the function can be
int CalculateSum (int a, int b) {
int sum;
sum = a + b;
return sum;
}
If you are the creator of the function you can do it however you want, but if the function is already defined you will have to use it as the definition begins.
When you write a function, you need to split your mind into two different personas. You have the developer who's writing the function, we'll call them FuncDev, and you have the developer who will be calling that function, we'll call them CallDev.
When FuncDev is writing the function, they need to think about what CallDev needs the function to do and in what situations they'll be calling it. What information does CallDev have when they're calling the function? What do they want the function to actually do or give back?
In the case of calculateSum, CallDev is going to have two numbers that they want to find the sum of. And FuncDev only needs two numbers to correctly calculate a sum. So everyone's in agreement here: to call calculateSum, you should provide two numbers and get a number back (that's the sum of those two).
All of this information can be found in the function header:
//- This function will return (or give back) an integer
//| - This function requires two integers to do its job
//v v
int calculateSum(int a, int b) {
You don't need to also include an int sum parameter because A. that's not something CallDev will have at the time of calling the function. The whole point they're calling is to get a sum in the first place! And B. that's not something FuncDev needs to calculate the sum. So you'd be imposing an extra condition on anyone calling the function without gaining anything in the function implementation.
Also, everything that happens inside the curly braces in the function logic itself, CallDev should never need to know about. Whether FuncDev decides to make a int sum variable to hold the sum before they return it, etc... shouldn't matter.
Usually, when I'm developing, I'll make the function calls before I even write the functions. So in your case, I may be going along and think "Hmm, I really need the sum of two numbers here. I have two numbers onhand, it'd be nice if I could just call calculateSum(num1, num2) and get the value I need." So I'll actually just write the call to the function and keep going1.
1. In actuality, this looks like writing tests when applicable for the function and then writing it. But the premise is the same. I'm defining the behavior, inputs and outputs of the function all before I write it.
I seen weird for loop syntax in C++. Please see following program.
#include <iostream>
using namespace std;
int main()
{
int num, count = 0;
int array[]= {1,1,2,3,4,1,3,2,9,8,7};
cout<<"Which number would you like to know about how many times it appeared?"<<endl;
cin>>num;
for (int i:array)
{
if (i == num)
++count;
}
cout<<"Number "<<num<<" appeared "<<count<<" times in the array"<<endl;
return 0;
}
It is successfully run on GCC Linux platform.
Reference link Here.
So, My question is, Is it the correct way to use for loop in C++?
Also, Is for (int i:array) equivalent to for ( int i:array ; ; )?
Sorry for my poor english. Thanks in advance.
There are now (since C++11) two distinct syntaxes for for-loops, the old C-style:
for (initialization; test; increment)
and the new
for (declaration: container)
In the new syntax, the declaration declares a variable which is successively given the value of each element of the container. Common values of "declaration" are auto val, const auto val, auto& val, and const auto& val, depending on whether you want a reference to the value in the container or a copy, and whether you want the value constant or not.
Both syntaxes are correct. It rather depends what you want to do in the loop. My preference is to use the range based for unless I am going to need the loop counter or iterator ... in which case I fall back on the old style for.
See http://en.cppreference.com/w/cpp/language/range-for for the gory details of the specification (and what is meant by "container").
The syntax for (int i:array) iterates through each element in the array, compared to for (int i = 0; i<sizeof(array); i++) which creates a counter that automatically increments on each iteration of the loop. The counter can then be used to access elements of the array with array[i]
As for which one you'd use, it depends on what you want to do. In your example there isn't a need to keep track of which iteration of the loop you are on, so the former will work fine. If you wanted to, say, print the iteration number each time then you would use the latter.
P.S. your English is perfect :)
This is what I want to achieve. In my test fixture I want to call a helper functions with a parameter n to tell the test fixture how many initialization sequences should be expected. Some parameters used in the sequences are stored in three std::vector containers; fileDescriptor, handle, selectionObject.
What I have written is this:
void MyTest::init_Ok(uint32_t n)
{
for (uint32_t i = 0; i < n; ++i)
{
fileDescriptor.push_back(i); // FDs starting at 0
handle.push_back(reinterpret_cast<void*>(18 + i)); // handles starting at 18
selectionObject.push_back(555 + i); // SOs starting at 555
EXPECT_CALL(MyMockApi::getApi(), initialize(Pointee(nullptr), StrEq("InitString"), MyMatcher()))
.WillOnce(DoAll(SetArgPointee<0>(handle[i]),
Return(INIT_OK)));
EXPECT_CALL(MyMockApi::getApi(), selectionObjectGet(handle[i], Pointee(nullptr)))
.WillOnce(DoAll(SetArgPointee<1>(selectionObject[i]),
Return(SELECTION_OK)));
EXPECT_CALL(MyMockApi::getApi(), finalize(handle[i]))
.WillOnce(Return(FINAL_OK));
}
}
I know why it's not working. It is expected that all calls to initialize will be identical but yet I want to perform different actions (parameter depending on loop counter i) for the first, second, third, ..., nth call. The current implementation will only expect one call to initialize no matter parameter n. Is it possible to fix this and keep it a loop somehow, or do I have to add the actions with a WillOnce line for each i? This would mean i have to check n and add different number of WillOnce lines for different possible values of n, which i really want to avoid.
One way could be to use Invoke. You can write a function which will have access to the handles container and a running member/static variable(lets say counterVar) which will indicate the number of times the function is hit. Based on the value of counterVar, you can decide the logic.
.WillRepeatedly(Invoke(<your function>))
Something like:
EXPECT_CALL(MyMockApi::getApi(), initialize(Pointee(nullptr), StrEq("InitString"), MyMatcher()))
.WillRepeatedly(Invoke(successfulInitialize));
ReturnCode successfulInitialize(void* op, std::string msg)
{
static int counterVar = 0;
*op = handles[counterVar++];
return INIT_OK;
}
I am generalizing another problem I have that has a similar recursive call. In my case, the variables being used are strings, so I can't simply pass by value to avoid the code before and after the recursive call in the loop. Is there a way to turn this into an iterative loop? Please assume that the code before and after the recursive call in the loop cannot be changed to make this specific instance work.
This code tests to see if the sum of any combintion of ints from nums adds up to zero. The original value for index is 0, and max is the maximum number of numbers I want to add up in any given solution.
For further clarification, the numbers can be repeated, so I can't just try all possible combinations, because there are infinitely many.
void findSolution(const vector<int>& nums, vector<int>& my_list, int& mySum,
int index, const int max)
{
if(mySum == 0) {
/* print my_list and exit(0) */
}
if(index < max) {
for(int i = 0; i < nums.size(); ++i) {
my_list.push_back(nums[i]);
mySum += nums[i];
findSolution(nums, my_list, mySum, index+1, max);
mySum -= nums[i];
my_list.pop_back();
}
}
}
Maintain a manual stack.
In your case the only independent states of the recursive call are the value of I and the value of index. Index is just the recursive call depth.
Create a std vector of int called your stack, reserve it to max. Replace the loop with while stack true.
Before entering the loop, push zero on the stack.
Break the cod in your loop into 3 parts. A B and C. A is before recursive call, B is what you recursively call, and C is after. Included in C is the increment at the top of the loop, which happens after C in the original code.
The first thing you do in the loop is check if the top of the stack is nums size or bigger. If so, pop the stack, then execute C and continue unless stack is empty, in which case break.
Then execute A. Then push 0 on the stack and continue if the stack size is less than max. Then execute C. You can remove the C code duplication with a flag variable.
Remember that the top of the stack replaces any references to I. Basically we are replacing a recursive call which automatically makes a stack for us with manually maintaining the same stack, but only storing the absolute least amount we can get away with. The start of the loop does double duty as both the end of a recursive call and the start of the loop, so we can do away with goto.
Give it a try, and worry about the explanation after you have seen it. The stuff about the flag variable makes more sense after the code is in place.