I am trying to write a recursive function that has two inputs, first and second, which both are strings(from ). The function should print all rearrangements of letters in first, followed by second. For example, if first is the string “CAT” and second is the string “MAN”, then the function would print the strings TACMAN, ATCMAN, CTAMAN, TCAMAN, ACTMAN, and CATMAN.

And the stopping case of the function occurs when the length of first has zero characters. There are two string members are useful in the program. The following is the precondition and postcondition of these two string functions.

//postcondition: The specified number of copies of c have been
//inserted into the string at the indicated position.
//Existing characters that used to be at or after the given position have been shifted right
//one spot
}
void string::erase(size_type position, size_type n)
{

// delete c[]; or c[] = NULL;
}

int main()
{
char c[5];

insert(,,); //First function call, so it starts at one
}

Please give me ideas and suggestions. I am looking for specific ideas that can help me put my thinking comments to C++ code.

Thank you.

November 12th, 2007, 04:48 AM

Graham

Re: Recursive Functions

OK, first hint: you're going to make life very difficult for yourself if you try to handle the whole string as a unit. Handle them separately and only combine the result when you have to. Even though your approach may well (eventually) work for this one case, you need to be thinking in terms of generalising the problem - what if you change the string lengths? What if you need to permute both strings? A good design choice now can really simplify changes that may be needed in the future.

so:

Code:

string string1 = "CAT";
string string2 = "MAN";

for each permutation of string1
print string1 + string2

Now you only have to figure out how to permute the n characters of string1. Try looking up "permutation algorithms".

Should you need to extend it to permute string 2 as well, then it becomes:

Code:

string string1 = "CAT";
string string2 = "MAN";

for each permutation of string1
for each permutation of string2
print string1 + string2

See how simple it becomes to extend the original problem?

November 12th, 2007, 04:06 PM

GaganW18

permute two strings using recursion? help!!!

I have figured out the "permutation" for one part and I need help with "printing" part.

Here are the conditions for my functions:

1) the stopping case of the function occurs when the length of first has zero characters

2) for void string::insert :
-The specified number of copies of c have been inserted into the string at the indicated position.
-Existing characters that used to be at or after the given position have been shifted right one spot.

3) for void string::erase :
-n characters have been removed from the string, beginning at the specified position.