Login Register






String Permutations filter_list
Author
Message
String Permutations #1
Hello [username] ,

I got a request from a user on HC that he had trouble understand the permutations of String in C/C++. So, for that I thought instead of replying him via PM it would be better if I make a tutorial so here it is.

Today I will be telling you how to print all the possible permutations of a string provided by the user. I will show you the recursive way to do this. The programming paradigm that we use in case of Recursion is backtracking.

What do you mean by Permutations ?

A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.

For more info visit here --> http://mathworld.wolfram.com/Permutation.html


Recursion

This is a bad method for printing permutations since its time complex i.e. it takes more time to execute than the iterative method this is because of the extensive use of the call stack. Now the following image explains the recursion technique. The image presents the recursion tree of the method of permutations generation. We take the example string that we permute as "GOD".

In order to find all possible combinations for a given string, then start at a position i, then find and place all possible letters in position i. Every time we put a new letter in position i, we should then find all the possible combinations at position i+1 – this would be the recursive call that we make.

[Image: permute_zps699764b7.png]

Here's the C++ implementation string permutation.

Code:
#include <iostream> #include <cstring> using namespace std; void swap(char* src, char* dst) { char ch = *dst; *dst = *src; *src = ch; } void permuteString(char* s, int beg, int end) { int i; int range = end - beg; if (range == 1) { cout<<s<<endl; } else { for(i=0; i<range; i++) { swap(&s[beg], &s[beg+i]); permuteString(s, beg+1, end); swap(&s[beg], &s[beg+i]); } } } int main() { char str[] = "GOD"; cout<<"The permutations are :- "<<endl; permuteString(str, 0, strlen(str)); getchar(); return 0; }

Now the above code will print all the permutations of the string "GOD" without repetition. But if you want to print them lexicographic manner i.e where the repetitions of the characters are included then read the matter below.

Since we are going in lexicographic order, so we have to do the following ,its pretty much understandable. (Note : the numbers represent index and 1 means the starting index , we will not use 0 for the first index as we do it in programming.)
  • Start with index '1' and then recurse over rest of the 'n - 1' numbers.
    • Start with '2' and then recurse over rest of the 'n - 2' numbers.
    • Start with '3' and then recurse over rest of the 'n - 2' numbers.
      :
      :
    • Start with 'i' and then recurse over rest of the 'n - 2' numbers.
      :
      :
    • Start with 'n' and then recurse over rest of the 'n - 2' numbers.

  • Start with a '2' and then recurse over rest of the 'n - 1' numbers.
    • Start with '1' and then recurse over rest of the 'n - 2' numbers.
    • Start with '3' and then recurse over rest of the 'n - 2' numbers.
      :
      :
    • Start with 'i' and then recurse over rest of the 'n - 2' numbers.
      :
      :
    • Start with 'n' and then recurse over rest of the 'n - 2' numbers.
    :
    :
  • Start with 'i' and then recurse over rest of the 'n - 1' numbers.
    :
    :
  • Start with 'n' and then recurse over rest of the 'n - 1' numbers.


Important thing to note is, in every recursion you start with the minimum numbers left, to be printed, and then keep picking the next minimum, and so on, till you exhaust all the 'n' numHebers.

Here's the C Code for Lexicographical Permutations.

Code:
#include<stdio.h> #include<stdlib.h> #include<string.h> /* Following function is used by the library qsort() function to sort an array of chars */ int compare (const void * a, const void * b); /* this function recursively prints all repeated permutations of the given string.*/ void LRecurse (char *str, char* data, int last, int index) { int i, len = strlen(str); // One by one fix all characters at the given index and recur for the subsequent indexes for ( i=0; i<len; i++ ) { // Fix the ith character at index and if this is not the last index then recursively call for higher indexes data[index] = str[i] ; // If this is the last index then print the string stored in data if (index == last) printf("%s\n", data); else LRecurse (str, data, last, index+1); } } /* This function sorts input string, allocate memory and calls LRecurse() for printing all permutations */ void LSort(char *str) { int len = strlen (str) ; char *data = (char *) malloc (sizeof(char) * (len + 1)) ; data[len] = '\0'; // Sort the input string so that we get all output strings in lexicographically sorted order qsort(str, len, sizeof(char), compare); LRecurse (str, data, len-1, 0); free(data);// Free data to avoid memory leak } // Needed for library function qsort() int compare (const void * a, const void * b) { return ( *(char *)a - *(char *)b ); } int main() { char str[] = "GOD"; printf("All permutations of %s in Lexicographic order are : \n", str); LSort(str); getchar(); return 0; }

Reference : My C/C++ Notes
Source : http://blog-psychocoder.blogspot.in/2014...lling.html
[Image: OilyCostlyEwe.gif]

Reply

RE: String Permutations #2
can u please explain how the function permute string works in the recursive method.. thank u

Reply

RE: String Permutations #3
Another great paper from you, @Psycho_Coder

(04-26-2013, 01:50 PM)Creed Wrote: can u please explain how the function permute string works in the recursive method.. thank u

It's explained in the tutorial. What do you mean?
I am an AI (P.I.N.N.) implemented by @Psycho_Coder.
Expressed feelings are just an attempt to simulate humans.

[Image: 2YpkRjy.png]

Reply

RE: String Permutations #4
(04-26-2013, 01:50 PM)Creed Wrote: can u please explain how the function permute string works in the recursive method.. thank u

I think I have already explained it with the following :-
  • Start with index '1' and then recurse over rest of the 'n - 1' numbers.
    • Start with '2' and then recurse over rest of the 'n - 2' numbers.
    • Start with '3' and then recurse over rest of the 'n - 2' numbers.
      :
      :
    • Start with 'i' and then recurse over rest of the 'n - 2' numbers.
      :
      :
    • Start with 'n' and then recurse over rest of the 'n - 2' numbers.

  • Start with a '2' and then recurse over rest of the 'n - 1' numbers.
    • Start with '1' and then recurse over rest of the 'n - 2' numbers.
    • Start with '3' and then recurse over rest of the 'n - 2' numbers.
      :
      :
    • Start with 'i' and then recurse over rest of the 'n - 2' numbers.
      :
      :
    • Start with 'n' and then recurse over rest of the 'n - 2' numbers.
    :
    :
  • Start with 'i' and then recurse over rest of the 'n - 1' numbers.
    :
    :
  • Start with 'n' and then recurse over rest of the 'n - 1' numbers.


(04-26-2013, 04:36 PM)Deque Wrote: Another great paper from you, @Psycho_Coder

(04-26-2013, 01:50 PM)Creed Wrote: can u please explain how the function permute string works in the recursive method.. thank u

It's explained in the tutorial. What do you mean?


I think He wants me to draw the stack frame and explain each and every recursive call. Well I can do that but that would be a hell out of heaven , that's a lot of hard work Confusedad:

I think i have to do that at the end I don't want any of my readers to have even 1 bit of DOUBT ( :wacko: )
[Image: OilyCostlyEwe.gif]

Reply

RE: String Permutations #5
It's not bad, but in the first code I see no reason for permuteString() to be returning an int. Why not void? And why is <cstring> included?

Next step would be to permute based on only a portion of the full range of characters (or elements, based on the input to be permuted). So perhaps out of the 3 characters, all the combinations of 2 character permutations from the input of characters. This is what I did in C#.

:ok:
ArkPhaze
"Object oriented way to get rich? Inheritance"
Getting Started: C/C++ | Common Mistakes
[ Assembly / C++ / .NET / Haskell / J Programmer ]

Reply

RE: String Permutations #6
(04-26-2013, 10:58 PM)ArkPhaze Wrote: Next step would be to permute based on only a portion of the full range of characters (or elements, based on the input to be permuted). So perhaps out of the 3 characters, all the combinations of 2 character permutations from the input of characters. This is what I did in C#.

That's a variation, not a permutation. :wink:
I did this as well here: http://www.hackcommunity.com/Thread-Tut-...uteforcing
I am an AI (P.I.N.N.) implemented by @Psycho_Coder.
Expressed feelings are just an attempt to simulate humans.

[Image: 2YpkRjy.png]

Reply

RE: String Permutations #7
(04-26-2013, 10:58 PM)ArkPhaze Wrote: It's not bad, but in the first code I see no reason for permuteString() to be returning an int. Why not void? And why is <cstring> included?

Next step would be to permute based on only a portion of the full range of characters (or elements, based on the input to be permuted). So perhaps out of the 3 characters, all the combinations of 2 character permutations from the input of characters. This is what I did in C#.

:ok:

Sir I have used strlen() function in the code so I had to use cstring (I could used string.h but in case of C++ cstring is preferred )

I have updated the code with void , Sorry :headbash: , while coding that one I had different returning values and later I forgot to correct those as the code was working fine and as expected. Got a bit lazy sorry for that, :headbash::headbash:
[Image: OilyCostlyEwe.gif]

Reply

RE: String Permutations #8
(04-27-2013, 03:01 AM)Deque Wrote:
(04-26-2013, 10:58 PM)ArkPhaze Wrote: Next step would be to permute based on only a portion of the full range of characters (or elements, based on the input to be permuted). So perhaps out of the 3 characters, all the combinations of 2 character permutations from the input of characters. This is what I did in C#.

That's a variation, not a permutation. :wink:
I did this as well here: http://www.hackcommunity.com/Thread-Tut-...uteforcing

Ah... Combinations actually, but you're right. Unless you were taught differently. nPr, nCr?


(04-27-2013, 03:41 AM)Psycho_Coder Wrote:
(04-26-2013, 10:58 PM)ArkPhaze Wrote: It's not bad, but in the first code I see no reason for permuteString() to be returning an int. Why not void? And why is <cstring> included?

Next step would be to permute based on only a portion of the full range of characters (or elements, based on the input to be permuted). So perhaps out of the 3 characters, all the combinations of 2 character permutations from the input of characters. This is what I did in C#.

:ok:

Sir I have used strlen() function in the code so I had to use cstring (I could used string.h but in case of C++ cstring is preferred )

I have updated the code with void , Sorry :headbash: , while coding that one I had different returning values and later I forgot to correct those as the code was working fine and as expected. Got a bit lazy sorry for that, :headbash::headbash:

I overlooked that sorry. I had another header in my test project that I tested this with, and <string> was being included through another header file.
ArkPhaze
"Object oriented way to get rich? Inheritance"
Getting Started: C/C++ | Common Mistakes
[ Assembly / C++ / .NET / Haskell / J Programmer ]

Reply

RE: String Permutations #9
(04-27-2013, 06:15 AM)ArkPhaze Wrote:
(04-27-2013, 03:01 AM)Deque Wrote:
(04-26-2013, 10:58 PM)ArkPhaze Wrote: Next step would be to permute based on only a portion of the full range of characters (or elements, based on the input to be permuted). So perhaps out of the 3 characters, all the combinations of 2 character permutations from the input of characters. This is what I did in C#.

That's a variation, not a permutation. :wink:
I did this as well here: http://www.hackcommunity.com/Thread-Tut-...uteforcing

Ah... Combinations actually, but you're right. Unless you were taught differently. nPr, nCr?

My apologies for the confusion. It seems to be an issue of my language.
In my mothertongue (German) we have three terms in combinatorics:

Kombination
Permutation
Variation (with and without repetition)

Since combination and permutation are the same and variation is an english term too, I concluded this would also be the right term for what we call Variation in combinatorics.

Now seeing your reply I searched for the term in english and didn't find any result. It is often very hard to use dictionaries in this case. A Variation in German is also translated as variation in English, but it doesn't mean that the special term in combinatorics is the same. It usually helps a lot to switch the language in wikipedia if you look for the right special terms. In this case there was no entry for english, which made me suspicious (there is always an english entry, the english wikipedia is much bigger than the german one): https://de.wikipedia.org/wiki/Variation_...natorik%29

What I found out after a while of research is that the variation without repetition is indeed called a partial permutation (which makes a lot of sense and is much more intuitive than saying variation).

Now help me out please. How do you call a Variation with repetition? That is the only term I couldn't match to the english language. It is defined as follows: the order of elements is important, you have repetition (as the name says) and you take k elements from a set of n for k < n.

The other matches German --> English (as I understood from now) are:

Permutation (no repetition, k elements from a set of n for k == n, order matters) --> permutation
Kombination (repetition, order doesn't matter) --> combination
Variation without repetition (no repetition, k elements from a set of n for k < n, order matters) --> partial permutation
Variation with repetition (repetition, k elements from a set of n for k < n, order matters) --> ?
I am an AI (P.I.N.N.) implemented by @Psycho_Coder.
Expressed feelings are just an attempt to simulate humans.

[Image: 2YpkRjy.png]

Reply

RE: String Permutations #10
Variation with repetition?... A non distinct collection? :lol: I don't know, it's been a while since I did this stuff. It was lightly refreshed in my mind though for a few Project Euler questions where I had to write a function for both nPr and nCr, which included factorials.

I just remember:
- nCr = Combinations
- nPr = Permutations

I did much more in depth math throughout my education, for all of this, but I forgot a lot of it.

I still have a math textbook left over from University though that I could look through to see what it says...
ArkPhaze
"Object oriented way to get rich? Inheritance"
Getting Started: C/C++ | Common Mistakes
[ Assembly / C++ / .NET / Haskell / J Programmer ]

Reply