1

Hello I'm a beginner in cpp programming. I was reading some examples of cpp programs and i see this question but i couldn't solve it : There's an algorithm below starting from 0 as each step that goes forward you should replace all 0's with 01 and 1's 10. The input is the number of stage and the output is the number that generates solve this with recursive function.

Here is the example:

1)0
2)01
3)0110
...
Input:3
Output:0110

I tried this:


string generate(string &algorithm, int n) {

    if (n <= 0)
        return algorithm;
      //confused?

}
 
int main() {
    string algorithm = "0";
    string new_algorithm;
    long long int n, k;
    cin >> n >> k;
    new_algorithm = generate(algorithm, n);

    return 0;
}

   

It should be in recursive form but I can't do it straight too! Any help would be appreciated!

3
  • What have you tried? Where did you get stuck? Please show a minimal reproducible example Commented Mar 1, 2022 at 12:21
  • 1
    That isn't even valid C++ code, and certainly not a proper minimal reproducible example. I'm curious where you saw this question while 'reading some examples of cpp programs' and did not see a possible solution. Regardless, understand the algorithm. You'll notice each generation past (1) starts with the identical string from the prior generation, then appends the inverse. Inner-string substitution isn't required. It's just a copy and a bunch of appends, then a recursion, with a base-case of bolting when the stage has descended to 1 or lower. Commented Mar 1, 2022 at 12:47
  • I added some code Commented Mar 1, 2022 at 12:51

1 Answer 1

2

The number of recusions is given so the function will look something like this:

std::string replace_recursive(const std::string& in, int n) {
    if (n <= 0) return in;

    std::string next = replace(in);

    return replace_recursive(next,n-1);
}

It has a stop condition, it executes a single step (by calling replace) and it has the recursive call.

All you need to add is going from in to next. For this it is easiest to use a range based loop and construct the new string by appending. I am trying to not give away the whole solution:

std::string replace(const std::string& in) {
     std::string result;
     for (const auto& c : in) {
         if (c == ....) result += " ... ";
         else if (c = ....) result += " .... ";
     }
     return result;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.