alphaRomeoNovember
alphaRomeoNovember

Reputation: 3

Repeated Function call in the following program in C++

I have to write a programs that takes an input of string which has some '$' and digits. The output of the program is set of all possible strings where the '$ in the string is replaced by all the other digits. I have written the following code for it.

#include<bits/stdc++.h>

using namespace std;

int numberOf(string in)
{
    int count = 0;
    for(int i = 0; i <= in.size()-1; i++)
        if(in[i] == '$')
            count++;

    return count;
}
void solve(string in, string in1, vector <string> &s,
    int index)
{

    if(numberOf(in) == 0)
    {
        s.push_back(in);
        return;
    }

    if(index == in.size())
    {
        return;
    }

    if(in1.empty())
    {
        return;
    }
    
    else
    {
        if(in[index] == '$')
        {
            string in2 = in;
            in2[index] = in1[0];
            string in3 = in1;
            in3.erase(in3.begin());
            solve(in2, in1, s, index+1);
            solve(in, in3, s, index);

            return;
        }
        else
        {
            solve(in, in1, s, index+1);
            return;
        }
    }
}

void replaceDollar(string in)
{
    string in1 = in;
    int count = 0;
    for(int i = 0; i <= in.size()- 1; i++)
    {
        if(in[i] != '$')
        {
            in1.push_back(in[i]);
            count++;
        }
    }
    count = in.size() - count;
    cout << "Number is " << count << "\n";

    vector <string> s;
    solve(in, in1, s, 0);

    for(auto i = s.begin(); i != s.end(); i++)
        cout << *i << " ";
    cout << "\n";

}

int main()
{
    int t;
    cin >> t;
    while(t--)
    {
        string in;
        cin >> in;
        replaceDollar(in);
    }
return 0;
}

For following input

1
$45

The expected output should be

445 545

But it returns

445 545 445 545

Can anyone please explain why is it outputting repeated strings? Also can anyone suggest a better approach to this question? Thanks in advance!

Upvotes: 0

Views: 68

Answers (1)

kmiklas
kmiklas

Reputation: 13443

Assuming that this is homework:

  1. Start over. Your code is way too complex for this problem.
  2. I would treat everything as type char
  3. Loop/iterate over said string, using std::string::replace() to replace each instance of $ with each digit.
    -- If your teacher doesn't want you using std libraries, then add another loop and compare yourself.
    3a. Of course, add a check, so that you don't replace $ with $
  4. Create a new copy of the string on each iteration.
  5. Print each to stdout as you create them.

See this post:

How to replace all occurrences of a character in string?

p.s. Pro tip: don't use using namespace. Use the full namespace in your calls; e.g.:

Bad

using namespace std;
string = "hello world";

Good

std::string = "hello world";

Upvotes: 1

Related Questions