RockersDriven
RockersDriven

Reputation: 15

Writing the Base Case for a recursive program that prints out all the permutations of a given string in C++

The function is called as: Perm( "xyz", "abc" ); then it would print:
xyzabc xyzacb xyzbac xyzbca xyzcab xyzcba The xyz is fixed and has all permutations of abc concatenated to it.

I started a for Loop to deal with the general case, and part of the base case but I am having a hard time figuring out where I am going wrong.

#include <string>

#include <iostream>
using namespace std;

void Perm(string fixedPart, string permPart)
{

    if (permPart.length() == 1) {

        cout << fixedPart << permPart << endl;
    }
    else {
    for (int i = 0; i < permPart.length() - 1; i++) {
          Perm(fixedPart + permPart[i] , 
          permPart.substr(0, i) + permPart.substr(i + 1,permPart.length()-1));
    }
    }
}

int main(){

    // Don't touch main!!!

    string s;

    cout << "Enter a String: ";
    cin >> s;
    cout << s << endl;

    cout << "Perms are: " << endl;
    Perm("xyz", s);

}

Upvotes: 0

Views: 201

Answers (1)

Venkatesh Nandigama
Venkatesh Nandigama

Reputation: 518

Problem is not with base case, Just change the for loop condition to

i < permPart.length()

last character also should be swapped with other characters in the permutation

Upvotes: 1

Related Questions