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

#1 KYA   User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3202
  • View blog
  • Posts: 19,235
  • 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   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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.....
Was This Post Helpful? 0
  • +
  • -

#3 Karel-Lodewijk   User is offline

  • D.I.C Addict
  • member icon

Reputation: 454
  • View blog
  • 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.
Was This Post Helpful? 0
  • +
  • -

#4 axnjxn   User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • 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
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1