String Permutation

Page 1 of 1

3 Replies - 2558 Views - Last Post: 03 July 2012 - 10:06 AM

#1 KYA

• Wubba lubba dub dub!

Reputation: 3207
• Posts: 19,239
• Joined: 14-September 07

String Permutation

Posted 21 July 2008 - 11:28 AM

Description: Implement within your program to find all permutations of a given string.A short solution to the problem of finding all the variations of a string.
```/*
* KYA
* String Permutation
* @ params: char array, begin, and end of array
* 7-21-08
*/

#include <iostream>
#include <string>
using namespace std;

void swap(char* first, char* second)
{
char ch = *second;
*second = *first;
*first = ch;
}

int permute(char* set, int begin, int end)
{
int i;
int range = end - begin;
if (range == 1) {
cout << set << endl;
} else {
for(i=0; i<range; i++) {
swap(&set[begin], &set[begin+i]);		//initial swap
permute(set, begin+1, end);				//recursion
swap(&set[begin], &set[begin+i]);       //swap back
}
}
return 0;
}

//Example Implementation -- Up to you on how to use
int main()
{
char str[255]; //string
cout << "Please enter a string: ";
cin.getline(str, 255); //take string
permute(str, 0, strlen(str)); //permutate the string
return 0;
}
```

Is This A Good Question/Topic? 0

Replies To: String Permutation

#2 crazylearner

Reputation: 0
• Posts: 2
• Joined: 04-April 11

Re: String Permutation

Posted 04 April 2011 - 04:09 AM

can anybody explain the logic behind this code.This code is gievn in every book but without any clear explaination.....

#3 Karel-Lodewijk

Reputation: 455
• Posts: 864
• Joined: 17-March 11

Re: String Permutation

Posted 05 February 2012 - 09:21 AM

std::next_permutation/std::prev_permutation is also an option.

#4 axnjxn

Reputation: 14
• Posts: 144
• Joined: 04-February 12

Re: String Permutation

Posted 03 July 2012 - 10:06 AM

This helped me greatly with understanding function recursion. I forced myself through each step to learn how the heck it worked. I feel much more comfortable with recursion now. Thanks KYA