From 3f1e345411053478ecc5f678ecc37da14f918420 Mon Sep 17 00:00:00 2001 From: Ujjwal <75884061+UG-SEP@users.noreply.github.com> Date: Tue, 30 Mar 2021 17:45:37 +0530 Subject: [PATCH] Permutation of String (#123) * added Permutation of String * permutation of string.c the main object is to explain the code more easy * permutation of string.c the main object is to explain the code more easy * updated readme * done all the recommend changes. * added link of Permutation of string * Update and rename Permutation of String.c to Permutation-of-String.c - rename according to the naming conventions - changed gets() to fgets() * update index readme of strings correctly linked [Permutation of String] after renaming of the file Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com> --- strings/README.md | 1 + strings/c-or-cpp/Permutation-of-String.c | 65 ++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 strings/c-or-cpp/Permutation-of-String.c diff --git a/strings/README.md b/strings/README.md index 7101b987..07bb97dd 100644 --- a/strings/README.md +++ b/strings/README.md @@ -8,6 +8,7 @@ 4. [Rabin Karp String Searching](c-or-cpp/rabin-karp.cpp) 5. [String Tokeniser](c-or-cpp/string-tokeniser.cpp) 6. [String Reversal](c-or-cpp/string-reverse.cpp) +7. [Permutation of String](c-or-cpp/Permutation-of-String.c) ### C# diff --git a/strings/c-or-cpp/Permutation-of-String.c b/strings/c-or-cpp/Permutation-of-String.c new file mode 100644 index 00000000..0d1fad5d --- /dev/null +++ b/strings/c-or-cpp/Permutation-of-String.c @@ -0,0 +1,65 @@ +// program to generate all permutation of the given string + +#include +#include +#include + +//declare permutation and swap functions +void permutation(char *,int,int); +void swap(char *,char *); +int main() +{ + char *s; + // dynamically creating string length + s=(char*)malloc(sizeof(char)*1000); + // getting string + fgets(s,1000,stdin); + // changing size to the length of string+1 to store null at end + s=realloc(s,strlen(s)+1); + //calling permutation + permutation(s,0,strlen(s)-1); +return 0; +} +void permutation(char *str,int s,int e) +{ //declare variables + static int count; + int i; + //base condition + if(s==e) + { + count++; + //Printing the string permutation's + printf("%d(%s)\n",count,str); + } + else + { + for(i=s;i<=e;i++) + { //swapping variables value + swap(str+s,str+i); + //calling permutation function + permutation(str,s+1,e); + //now swap the variables value and make it before one + swap(str+s,str+i); + } + } +} +//swap function +void swap(char *a,char *b) +{ + char temp; + //putting value in temp + temp=*a; + // putting value in a pointer + *a=*b; + //now putting value of temp in b pointer + *b=temp; + //swapping done +} +// Example: +//Input: abc +//Output: 1(abc) +// 2(acb) +// 3(bac) +// 4(bca) +// 5(cba) +// 6(cab)