Write a C program to print all permutations of a given string
August 2, 2009
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.
Source: Mathword(http://mathworld.wolfram.com/Permutation.html)
Below are the permutations of string ABC.
ABC, ACB, BAC, BCA, CAB, CBA
Here is a solution using backtracking.

# include <stdio.h>
/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
/* Function to print permutations of string
This function takes three parameters:
1. String
2. Starting index of the string
3. Ending index of the string. */
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j <= n; j++)
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j)); //backtrack
}
}
}
/* Driver program to test above functions */
int main()
{
char a[] = "ABC";
permute(a, 0, 2);
getchar();
return 0;
}
Algorithm Paradigm: Backtracking
Time Complexity: O(n*n!)
Important
Intelligent
Please see my series on this for a solution in Java, plus generating sub-permutations (for string "abcd" - all permutations of abcd, all permutations of bcd, all permutations of cd, etc), plus solving when duplicate characters are part of the string as in the examples, "aabc," "dddd," etc.
http://code.scottshipp.com/2013/04/12/permutations-generator-part-1/
http://code.scottshipp.com/2013/04/16/permutation-generator-part-2/
http://code.scottshipp.com/2013/04/21/permutation-generator-part-3/
http://code.scottshipp.com/2013/04/29/permutation-generator-part-4/
Excellent Post duude
How to print all possible permutations of strings?
!!
eg. for ABC, we have
AAA
AAB
AAC
ABA
ACA
....
CCC
i am kind of stuck into it
#include<iostream.h> #include<conio.h> #include<string.h> void permute(int); char s[50], temp[50]; int main() { cout<<"\nEnter String: "; cin>>s; cout<<"\n==========PERMUTATIONS==========\n"; permute(0); getch(); return(0); } void permute(int n) { for(int i=0; i<strlen(s); i++) if(i == strchr(s, s[i]) - s) { temp[n] = s[i]; if(n == strlen(s) - 1) cout<<temp<<"\n"; else permute(n+1); } temp[n] = NULL; }Can any one explain in detail how the complexity of the published program is n*n!??
A simple iterative function in java
public static void permute(String s) { char[] ca = s.toCharArray(); int l = ca.length; if(l == 1) { System.out.println(s); return; } int i = 0; int start = 0; while(start < l) { for(int j=i+1; j<l-1 && j+1 != l; j++) { swap(ca, j, j+1); System.out.println(new String(ca)); } swap(ca, i, l-1); System.out.println(new String(ca)); start++; } } public static void swap(char[] arr, int a, int b) { char t = arr[a]; arr[a] = arr[b]; arr[b] = t; }realized it will not work for length>3
#include
#include
void swap(char *n,int x,int y){
char temp;
temp = *(n+x);
*(n+x) = *(n+y);
*(n+y) = temp;
}
int main () {
char b[] = "abcd";
int size = strlen(b);
for(int k=0;k<size;k++){
char *a = b;
swap(a,0,k);
for(int j=0;j1;i--){
swap(a,i-1,i);
printf("%s \n",a);
}
}
}
return 0;
}
int main () {
char b[] = "abcd";
int size = strlen(b);
for(int k=0;k<size;k++){
char *a = b;
swap(a,0,k);
for(int j=0;j1;i--){
swap(a,i-1,i);
printf("%s \n",a);
}
}
}
i have 2 time commented but another for-loop for increment i is not showing in the program
@Shiv: Apologies for the inconvenience. Please try posing your comment between sourcecode tags. Without sourcecode tags, the comment is processed as normal html content and comparison operators may be considered as beginning of a html tag.
Permutation Without Repetition
# include <stdio.h> #include <string.h> #include <assert.h> /* Function to swap values at two pointers */ void swap (char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } /* Function to print permutations of string This function takes three parameters: 1. String 2. Starting index of the string 3. Ending index of the string. */ void permute(char *a, int i, int n) { int j; if (i == n) printf("%s\n", a); else { for (j = i; j <= n; j++) { swap((a+i), (a+j)); permute(a, i+1, n); swap((a+i), (a+j)); //backtrack } } } /* Driver program to test above functions */ int main( ) { char a[] = "AAABBBCCC"; int i,j; int size,cnt=0; int s = strlen(a)-1; size=s; for(i=0;i<=s;i++) { for(j=i+1;j<=s;j++){ if(a[i]==a[j]) // AB_B { a[j]='-'; //remove a[j] and slide other element there } } } j=s; for(i=0 ;i<s;i++) { if(a[i]=='-') { while(a[j]=='-'){ a[j]=' '; j--; size--; } if(i<j){ a[i]=a[j]; a[j]='-'; } } } printf("\nA is :"); puts(a); permute(a, 0, size); // getchar(); return 0; }Piece of code that collects all permutations into collection. Beware of long strings. It goes out of memory.
void permutate(String st, Queue<String> q) { if (st.length() > 1) { char el = st.charAt(0); st = st.substring(1); permutate(st, q); while (!q.isEmpty() && q.peek().length() == st.length()) { String _st = q.poll(); for (int i = 0; i <= _st.length(); i++) { StringBuilder sb = new StringBuilder(_st); sb.insert(i, el); q.offer(sb.toString()); } } } else { q.add(st); } }// printChars.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; void printChars(char *str, int len, int i, char *data, bool zeroFlag) { if(*(str+i) == '*' && zeroFlag) { *(data+i) = '0'; i++; } if(*(str+i) == '*' && !zeroFlag) { *(data+i) = '1'; i++; } while(*(str+i) != '*' && *(str+i) != '\0') { *(data+i) = *(str+i); i++; } if(*(str+i) == '*' && *(str+i) != '\0') { for(int j = i; j<len; j++) { printChars(str, len, j, data, zeroFlag); printChars(str, len, j, data, !zeroFlag); break; } } if(i >= len) { *(data+i) = '\0'; cout<<data<<endl; return; } } int _tmain(int argc, _TCHAR* argv[]) { char *str = "a*b*c*d*"; char *data = (char*)malloc(sizeof(char) * strlen(str)); printChars(str, strlen(str), 0, data, true); getchar(); return 0; }#include
#include
#include
void permute(int);
int count(char[], char);
char s[50], temp[50];
int perms = 0;
int main()
{
cout<>s;
cout<<"\n==========PERMUTATIONS==========\n";
permute(0);
cout<<"\nFREQUENCY = "<<perms;
getch();
return(0);
}
void permute(int n)
{
for(int i=0; i count(temp, s[i])))
{
temp[n] = s[i];
if(n == strlen(s) - 1)
{
cout<<temp<<"\n";
perms++;
}
else
permute(n+1);
}
}
temp[n] = NULL;
}
int count(char x[], char c)
{
int cnt = 0;
char *ptr = strchr(x, c);
while(ptr != NULL)
{
cnt++;
ptr = strchr(ptr+1, c);
}
return(cnt);
}
permute(0);
cout<<"\nFREQUENCY = "<<perms;
void permute(int n)
{
for(int i=0; i count(temp, s[i])))
{
temp[n] = s[i];
if(n == strlen(s) - 1)
{
cout<<temp<<"\n";
perms++;
}
else
permute(n+1);
}
}
temp[n] = NULL;
}
int count(char x[], char c)
{
int cnt = 0;
char *ptr = strchr(x, c);
while(ptr != NULL)
{
cnt++;
ptr = strchr(ptr+1, c);
}
return(cnt);
}
/* Following is the for loop that didn't get printed */
for(int i=0; i count(temp, s[i])))
{
/* works for all strings */
#include<iostream.h> #include<conio.h> #include<string.h> void permute(int); int count(char[], char); char s[50], temp[50]; int perms = 0; int main() { cout<<"\nEnter String: "; cin>>s; cout<<"\n==========PERMUTATIONS==========\n"; permute(0); cout<<"\nFREQUENCY = "<<perms; getch(); return(0); } void permute(int n) { for(int i=0; i<strlen(s); i++) { if(strchr(temp, s[i]) == NULL || (i == strchr(s, s[i]) - s && count(s, s[i]) > count(temp, s[i]))) { temp[n] = s[i]; if(n == strlen(s) - 1) { cout<<temp<<"\n"; perms++; } else permute(n+1); } } temp[n] = NULL; } int count(char x[], char c) { int cnt = 0; char *ptr = strchr(x, c); while(ptr != NULL) { cnt++; ptr = strchr(ptr+1, c); } return(cnt); }optimized code given by Venki
# include <stdio.h> /* Function to swap values at two pointers */ void swap (char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } /* Function to print permutations of string This function takes three parameters: 1. String 2. Starting index of the string 3. Ending index of the string. */ void permute(char *a, int i, int n) { int j; if (i == n) printf("%s\n", a); else { for (j = i; j <= n; j++) { if (i != j) swap((a+i), (a+j)); permute(a, i+1, n); if (i != j) swap((a+i), (a+j)); //backtrack } } } /* Driver program to test above functions */ int main() { char a[] = "ABC"; permute(a, 0, 2); getchar(); return 0; }You can use Lexicographic ordering to find all permutations :
import java.util.ArrayList;
import java.util.Iterator;
public class LexicographicPermutations {
private static String token = "abc";
private static int indexI = 0;
private static int indexJ = 0;
public static String Reverse(String substring,int lowIndex,int highIndex){
String subs = "";
for(int i = highIndex -1 ;i>lowIndex;i--){
subs = subs + substring.charAt(i);
}
return subs;
}
public static String swap(int L, int H, String subs){
char var = subs.charAt(L);
subs = subs.substring(0, L) + subs.charAt(H) + subs.substring(L+1);
subs = subs.substring(0, H) + var + subs.substring(H+1);
return subs;
}
public static void main(String args[]){
String perms = "";
String swapString = "";
String revString = "";
ArrayList permsArray = new ArrayList();
permsArray.add(token);
while(true){
for(int i=0;i<token.length()-1;i++){
if(token.charAt(i) < token.charAt(i+1)){
indexI = i;
}
}
for(int i=0;i<token.length();i++){
if(token.charAt(indexI) < token.charAt(i)){
indexJ = i;
}
}
if(indexI == indexJ){
break;
}
swapString = swap(indexI,indexJ,token);
revString = Reverse(swapString,indexI,token.length());
perms = swapString.substring(0,indexI + 1) + revString;
permsArray.add(perms);
indexI = 0;
indexJ = 0;
token = perms;
}
Iterator itr = permsArray.iterator();
while(itr.hasNext()){
System.out.print(itr.next() + " , ");
}
}
}
/**
*
* @author Dharmendra Singh
*/
public class PermutationOfStringCharsPassed {
private void getPermutationOfStringCharsPassed(char[] keys){
int size = (int) Math.pow(2, keys.length);
for(int i = 0 ; i < size ; i++){
for(int k = 0; k > k) & 1) == 1){
System.out.print(keys[k]);
}
}
System.out.println();
}
}
public static void main(String[] args) {
char[] keys = {'a','b','c','d'};
PermutationOfStringCharsPassed p = new PermutationOfStringCharsPassed();
p.getPermutationOfStringCharsPassed(keys);
}
}
//Dont know how my program got changed after posting
for(int i = 0 ; i < size ; i++){
for(int k = 0; k > k) & 1) == 1){
System.out.print(keys[k]);
}
}
System.out.println();
}
/* Paste your code here (You may delete these lines if not writing code) */
/**
*
* @author Dharmendra Singh
*/
public class PermutationOfStringCharsPassed {
private void getPermutationOfStringCharsPassed(char[] keys){
int size = (int) Math.pow(2, keys.length);
for(int i = 0 ; i < size ; i++){
for(int k = 0; k > k) & 1) == 1){
System.out.print(keys[k]);
}
}
System.out.println();
}
}
public static void main(String[] args) {
char[] keys = {'a','b','c','d'};
PermutationOfStringCharsPassed p = new PermutationOfStringCharsPassed();
p.getPermutationOfStringCharsPassed(keys);
}
}
A program will such a bad complexity is never useful to learn. Just see the complexity. n*n! .
Isn'it ? There should be better thing available or if not then its not useful to use such an algorithm.
jab permutations hi n! hain to, think before you comment.
exactly.....
tell me one thing....
will your code work for input 'AABBCC'??
#include
#include
#include
#include
main()
{
char ch[10],temp;
int i,k=1,b,f;
clrscr();
printf("enter the string");
gets(ch);
for(i=1;i<=strlen(ch);i++)
{
k=k*i;
}
for(i=0;i<k;i++)
{
b=((i%(strlen(ch))-1));
printf("%d",b);
temp = ch[b+1];
ch[b+1]=ch[b];
ch[b]=temp;
printf("%s\n",ch);
}
getch();
}
without any function calling...very simple..
little bit changes
---------------------------
#include
#include
#include
#include
main()
{
char ch[10],temp;
int i,k=1,b,f;
clrscr();
printf("enter the string");
gets(ch);
for(i=1;i<=strlen(ch);i++)
{
k=k*i;
}
f=strlen(ch);
for(i=0;i<k;i++)
{
b=i%(f-1);
temp = ch[b+1];
ch[b+1]=ch[b];
ch[b]=temp;
printf("%s\n",ch);
}
getch();
}
now it will work
it will work
-------------------
#include
#include
#include
#include
main()
{
char ch[10],temp;
int i,k=1,b,f;
clrscr();
printf("enter the string");
gets(ch);
for(i=1;i<=strlen(ch);i++)
{
k=k*i;
}
for(i=0;i<k;i++)
{
b=((i%(strlen(ch))-1));
printf("%d",b);
temp = ch[b+1];
ch[b+1]=ch[b];
ch[b]=temp;
printf("%s\n",ch);
}
getch();
}
simple check to avoid duplicates
/* Paste your code here (You may delete these lines if not writing code) */
[# include
/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
int check(char *arr,int i,int j)
{
if(i==j)
return 1;
for(;i< j;i++)
if(arr[i]==arr[j])
return 0;
return 1;
}
/* Function to print permutations of string
This function takes three parameters:
1. String
2. Starting index of the string
3. Ending index of the string. */
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j <= n; j++)
{
if(check(a,i,j)){
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j));
} //backtrack}
}
}
}
/* Driver program to test above functions */
int main()
{
char a[] = "APPLE";
permute(a, 0, 4);
getchar();
return 0;
}]
The code is working awesome.
Very good!
Keep it up!
little bit changes
---------------------------
#include
#include
#include
#include
main()
{
char ch[10],temp;
int i,k=1,b,f;
clrscr();
printf("enter the string");
gets(ch);
for(i=1;i<=strlen(ch);i++)
{
k=k*i;
}
f=strlen(ch);
for(i=0;i<k;i++)
{
b=i%(f-1);
temp = ch[b+1];
ch[b+1]=ch[b];
ch[b]=temp;
printf("%s\n",ch);
}
getch();
}
now it will work
A better code.....generate all permutation of given string ...takes care of duplicacy....nd presents permutations in lexicographic order... #include <stdio.h> #include<time.h> #include <string.h> #include<conio.h> void swap (char* pArray, int i, int j) { char temp = pArray[i]; pArray[i] = pArray[j]; pArray[j] = temp; } void perm (char* pArray, int size, int index) { int i,j,k; if(index==size) { printf("%s\n", pArray); } else { for(i = index; i < size; i++) { // for duplicacy if(pArray[i] == pArray[i+1]) { continue; } swap(pArray,i,index); for(j=index+1;j<=i;j++) { if(pArray[j]>pArray[i]) // for lexicographic { swap(pArray,j,i); } } perm(pArray,size,index+1); for(j=i;j>=index+1;j--) { if(pArray[j]<pArray[i]) { swap(pArray,j,i); } } swap(pArray,i,index); } } } void main () { char array[100]; clock_t start,end; clrscr(); gets(array); printf("Permutations:\n"); start=clock(); perm(array,strlen(array),0); end=clock(); printf("%f",(end-start)/CLK_TCK); getch(); }U r assuming that char array is alphabetically sorted. BTW Nice Code!
this code can permutate strings of any length and is written only for strings without any repeatation.
how do i improve so as to incorporate the strings with repeatation......
/* Paste your code here (You may delete these lines if not writing code) */
//***************anagrams**************//
//************************************** this code works only when there are no repeatations in the original string*************//
#include<iostream>
using namespace std;
int counter=0;
void print(char empty[],int size)
{
for(int i=0;i<size;i++)
{
cout<<empty[i];
}
cout<<endl;
}
void makecombination(char original[],char empty[],char comb[],int k,int& nc,int size)
{
nc=0;
int flag=0;
for(int i=0;i<size;i++)
{
flag=0; // {
for(int j=0;j<k;j++)
{
if(empty[j]==original[i]) // remove this code fragment
{ // to print permutations with repeatation
flag=1;
break;
}
}
if(flag==0) // }
{
comb[nc++]=original[i];
}
}
// cout<<"checks ";
// print(comb,nc);
}
void recurse(char original[],char empty[],int k,int size)
{
char *comb=new char[size];
int nc;
if(k==size)
{
counter++;
print(empty,size);
}
else
{
makecombination(original,empty,comb,k,nc,size);
k=k+1;
for(int i=0;i<nc;i++)
{
empty[k-1]=comb[i];
//cout<<"checks ";
//print(empty,size);
recurse(original,empty,k,size);
}
}
}
int main()
{
const int size=4;
int k=0;
char original[]="ABCD";
char empty[size];
for(int f=0;f<size;f++)
empty[f]='*';
recurse(original,empty,k,size);
cout<<endl<<counter<<endl;
return 0;
}
code doesn't work
missing case: string with repeat characters.
such as: abcdmabc
void swap(char str[], int i, int j){ char c; c = str[i]; str[i] = str[j]; str[j] = c; } void printStr(char str[], int k, int m){ if(k == m){ cout<<str<<endl; }else{ for(int i=k; i<=m; i++){ for(int j=k;j<i;j++) // remove the repeat characters if(str[j]==str[i]) goto nextloop; swap(str, i, k); printStr(str, k+1, m); swap(str, k, i); nextloop:; } } }/* Paste your code here (You may delete these lines if not writing code) */
[/code to print all puarmutation of integer array?]
how is this O(n*n!)?
Please help me in finding the time complexity of this approach.
void Anagram(int depth,char *Orig,int *track,char *Permut) { int i,j; if(depth==SIZE) { for(j=0;j<SIZE;j++) printf("%c",Permut[j]); printf("\n"); } else { for(i=0;i<SIZE;i++) { count++; if(!track[i]) { track[i]=1; //to indicate that ith character has been taken Permut[depth]=Orig[i]; Anagram(depth+1,Orig,track,Permut); track[i]=0; } } } } Please let me know if this is a better approach.What is the need to call swap once again after the permute function. I tried removing it and it still generates all the permutations except that order differs!
With 2nd Swap ->
ABC
ACB
BAC
BCA
CBA
CAB
Without 2nd Swap ->
ABC
ACB
CAB
CBA
ABC
ACB
@charanjeet, check your output (ABC repeated twice). It is backtracking step which restores the state once returned from previous explored node.
Without the second swap, there are no strings that are generated with B
Whats the need for calling swap after calling permute function?
I tried removing that, and its still generating all the permutations, only the order differs!
Please explain.
Not only order differs check carefully for input:abcd or inputs whose length greater than 3 there will be duplicates!!
plz give the program using loop in c and without any pointers or dynamic allocations... plz help
Let's say given 9 cities. How should I permute them and split it into 3 vehicles, so that each vehicles take 3 cities?
This programme works only for three letters, if I am using more than 3 then whats the option???
then just pass the length-1 instead of 2 in permute
permute(int input[]) { int n=size(input[]); int out[]=malloc(sizeof(input[])); int used[]=malloc(sizeof(input[])); for(int i=0;i<size(used[]);i++) { used[i]=0; } dopermute(input,0,n,out,used); } void dopermute(int input[],int level, int size, int out[],int used[]) { If(level>=size) { for(int i=0;i<size(out);i++) { printf("%c",out[i]); } return; } for(j=0;j<size;j++) { If used[i] continue; used[j]=1 out[level]=arr[j]; dopermute(input,level+1,size,out,used); used[j]=0; } }number is {1,2,3,4,5,6}it will print as by rotating 1 place it will look likjs 6,1,2,3,4,5
ArrayList<String> permutationsOf(String s) { ArrayList<String> result = new ArrayList<String>(); if (s.length() == 1) { result.add(s); return result; } else { char first = s.charAt(0); String rest = s.substring(1); ArrayList<String> simpler = permutationsOf(rest); for (String permutation : simpler) { ArrayList additions = insertAtAllPositions(first, permutation); result.addAll(additions); } return result; } }Hi Geeksforgeeks,
Neat Code. I just want to learn how you devised the backtracking algorithm for this problem?
//I mean I wanted to know the explanation of the tree given above.
-ckernel
hi
can any one suggest me good tutorial on c programming, i m new in programming , these days i m reading oop in c++ by lafore , please suggest me something that really helps me .. from the skretch ....
You can use use thinking in c++ Vol 1 By Bruce Eckel
http://www.digilife.be/quickreferences/books/thinking%20in%20c++,%20volume%201,%202nd%20edition.pdf
hi\
i copy the code in my complier but its not working
its prompt the following errors
1. 29 line , canno convert 'char * ', to 'char'
2. 29 line. type mismatch in parameter 'a' in call to ' permute( char, int
3, 32 line , 'a' is assigned a value that is never used
please help me i m new in programming
@omair hassan: The program has been tested with more than compilers and it works fine. See this for a sample run that works. Could you let us know the compiler you used and the exact code that you tried?
i am using turbo c ++
thank you so much for the reply . the codes runs finally at char swap (*x, *y) i was using char swap (a,b)
can u tell me what was the mistake , although i didn't understand the code
please help me ....
Following tutorial on pointers and function may help.
http://www.cs.cf.ac.uk/Dave/C/node10.html
that's so helpful thanks alot dude
The C book (http://publications.gbdirect.co.uk/c_book/) seems to be a good resource for C.
@sandeep
thank u so much dude
<?php function sort_string($str){ $arr = NULL; $len = strlen($str); for($i=0; $i<$len; $i++){ $arr[] = $str[$i]; } sort($arr); $str = ""; for($i=0; $i<$len; $i++){ $str = $str . $arr[$i]; } return $str; } function permute($str){ //base cases if ($str == NULL){ return ""; } $len = strlen($str); if ($len == 1){ return $str; } else if ($len == 2){ return $str ."," . $str[1] . $str[0]; } // the recursion else { $ans = ""; for($i=0; $i<$len; $i++){ // currenct char $char = $str[$i]; // the string without the selected char $str_b = substr($str,0,($i-1 < 0 ? 0 : $i)) . substr($str,$i+1, $len-$i-1); //build all the sub-permutations without char $sub_perm = permute($str_b); //now add char $ans = $ans . add_first_char($sub_perm, $char); } return $ans; } } function add_first_char($str, $char){ $ans = ""; $items = explode (',',$str); $len = sizeof($items); for($i=0; $i<$len; $i++){ $ans = $ans . "," . $char . $items[$i]; } // remove the first "," return $ans;// } $filename = $argv[1]; $handle = fopen($filename, "rb"); $line = ""; while (!feof($handle)) { $line = fgets($handle, 8192); $line = trim($line); if ($line != NULL) { $line = sort_string($line); $ans = permute($line); //remove first "," from the final response $ans = substr($ans,1,strlen($ans)-1); echo trim($ans) . "\n"; } } fclose($handle); return 0; ?>http://www.programmerinterview.com/index.php/recursion/permutations-of-a-string/
http://n1b-algo.blogspot.com/2009/01/string-permutations.html
Please explain how the time complexity is O(n!)??
see the for loop inside the func..permute where permute is called again and again 1 less than current n times
ie, n*n-1*n-2*......*1=O(n!)
or basically we could understand like this
eg ankit, we have find all possible permutations of the name ankit
as length of ankit is 5 thereforeforloop is called 5 times and then4 3 2 1 and so on as maximum permutations of agiven word of length n is n! therefore we can simply say the complexity is O(n!)......
hii..
i want a program to print the first letter of given sentence of each word and at the end the last word of given sentence also printed..
for ex:
the given string is: hii hello how are you
output:hhhayyou
like this... pls anybody tel me the code...
1.Read the line.
2.Tokenize the string.
3.For every token take the char at 0th position and store it in a another string or concatenate to your result string.
4.Repeat step 3 till tokens are there.
#include<stdio.h> #include<string.h> void print(char *s) { int i,word_start_index=0; printf("%c",s[0]); for(i=0;s[i]!='\0';i++) { if(s[i]==32) { printf("%c",s[i+1]); word_start_index=i+1; } } printf("%s\n",s+word_start_index); } int main() { char *s="hii hello how are you"; print(s); return 0; }& plzz give a flow chart also
plzz reply sharp..........write a program in c to print all posible permutations of abcde
#include <stdio.h> #define SIZE 3 int main(char *argv[],int argc) { char list[3]={'a','b','c'}; int i,j,k; for(i=0;i<SIZE;i++) for(j=0;j<SIZE;j++) for(k=0;k<SIZE;k++) if(i!=j && j!=k && i!=k) printf("%c%c%c\n",list[i],list[j],list[k]); return(0); }lol sandy your code is so naive, you see it will work for three chars only, no less, no more. its got no flexibility
Awesome website!!!
All are correct but i want the otput like
if the string is "abcd"
then the combinatio will
bcda
cdab
dabc
abcd
like that can u tell me
public static void main(String[] args) { char[] input = "abcd".toCharArray(); int j=0; for(int i=0;i<input.length;i++) { int count=0; j=i; while(count<input.length) { count++; System.out.print(input[j]); j=(j+1)%input.length; } System.out.println(); } }nice
really good site...for every question there is explanation
but how about if a want a permutation list of something like 1238596?
plz get me a program for this output
1
121
12321
121
12121
Guys,here is a very simple solution....
#include
#include
#include
using namespace std;
char a[10];
void func(char *a,int j=0)
{
if(j==strlen(a))
{
printf("%s\n",a);
}
char ch='';
for(int i=j;i<strlen(a);i++)
{
char t;
if(ch==a[i])
continue;
else
{
ch=a[j];
t=a[i];
a[i]=a[j];
a[j]=t;
func(a,j+1);
}
}
}
int main()
{
char a[10];
printf("Enter a String\n");
scanf("%s",&a);
printf("Permutations of string\n");
func(a);
getch();
return 0;
}
above program was not posted correctly...
use the new one...
it works when all elements of string are distinct otherwise some permutations will be repeated.
headers are iostream,string and conio.h.
#include
#include
#include
using namespace std;
char a[10];
void func(char *a,int j=0)
{
if(j==strlen(a))
{
printf("%sn",a);
}
for(int i=j;i<strlen(a);i++)
{
char t;
t=a[i];
a[i]=a[j];
a[j]=t;
func(a,j+1);
}
}
int main()
{
char a[10];
printf("Enter a Stringn");
scanf("%s",&a);
printf("Permutations of stringn");
func(a);
getch();
return 0;
}
@Ravinder & @Yugarsi, Here is your logic. How is it better, could you explain your view?
#include <iostream> using namespace std; void permute(char *a, int j = 0) { int len = strlen(a); if(j == len) { cout << a << endl; } for(int i = j; i < len; i++) { char t = a[i]; a[i] = a[j]; a[j] = t; permute(a, j+1); } } int main() { char a[] = "ABCD"; permute(a); return 0; }This kind of programs runs like O(f(n) * n!) or O(f() * 2^n) where is f(n) is polynomial in n. Any algorithm must generate all possible permutations.
actually your code/logic is the almost the same as the one posted by admin, you only replaced the swap fuction call by actual function, which could have been done automatically if swipe function was inline.
btw your program shows all permutations but the admins does not, or perhaps i made some glitch while copying.
@geeksforgeeks correct this code.for same type of word it is not working.
@amit khoth: Could you please provide a sample string for which it didn't work?
when two character are similar in a word.like aatif,aaaj etc,
Well, what do you think it should do? It's probably undefined for input like that.
actually it does not give all the permutations, for 3 chars there should be 3! = 6, right?
wanted someone who could critique or provide suggestions,
thank you
Btw Venki has given a correct code,
And for those who want it to not show repeating ones, put a condition before swaping, if the chars to be swapped are same continue ( i mean skip the statement continue; instruction and go for next.
Hey admin would you like my page on fb?? Its about coding too, ive made some awesome codes
Page is 'C programming'
facebook.com/CkCoders
http://anandtechblog.blogspot.com/2011/05/arra-y-problem.html
Great post!
Nice solution here as well:
http://www.programmerinterview.com/index.php/recursion/permutations-of-a-string/
The code mentioned above doesnt work correctly, if there are any repeated characters in the string, it would unncessarily print some strings multiple times ...
Working code for the same, which takes care of repeated chars as well:
# include <stdio.h> # include <conio.h> int printPermutations(char *str,int size, int pos) { int i; int total=0; if(pos==(size-1)) { puts(str); return 1; } total+=printPermutations(str,size,pos+1); for(i=pos+1;i<size;i++) { int j; for(j=pos;j<i;j++) if(*(str+j)==*(str+i)) break; if(j==i) { char tmp=*(str+pos); *(str+pos)=*(str+i); *(str+i)=tmp; total+=printPermutations(str,size,pos+1); tmp=*(str+pos); *(str+pos)=*(str+i); *(str+i)=tmp; } } return total; } int main() { char str[100]; int size,total; printf("Enter the string: "); gets(str); size=strlen(str); printf("\n\nAll permutations of the input string are:\n"); total=printPermutations(str,size,0); printf("\n\nThe total number of permutations of the given string is %d",total); getch(); return 0; }@rimu.nitrkl...Could You Please Through Some More Light ..I mean Can you write down the algorithm..step by step..its really nice way to programming that you have done..also..i think you TC is O(n^2)..isn't it..??
Waiting for your Explanation..??? Reply ASAP
i want a all combos of 7 letters
should i hav to use char
How the control again reaches to permute fn evenafter the i becomes 2
the first program gives repeated permutation in case of 122
how to correct it
plz help ??
in case of 122,it gives
122
212
221
212 //repeated
221 //repeated
Another way to do this : http://layerinside.blogspot.com/2011/02/permutation-of-string.html
Hey guys..I know Most of You Stuck with this Question..The 1st Backtracking approach..seems to typical..for understanding [points of view.....here i am posting a excellent so0lution fro problem hope this will help you ..lot..
Explanation
Let’s assume a given string S represented by the letters A1, A2, A3, ..., An
To permute set S, we can select the first character, A1, permute the remainder of the string to get a new list. Then, with that new list, we can “push” A1 into each possible position.
For example, if our string is “abc”, we would do the following:
1. Let first = “a” and let remainder = “bc”
2. Let list = permute(bc) = {“bc”, “cd”}
3. Push “a” into each location of “bc” (--> “abc”, “bac”, “bca”) and “cb” (--> “acb”, “cab”, “cba”)
4. Return our new list
import java.util.*; class Permutation { public static ArrayList getPerms(String s) { ArrayList permutations = new ArrayList(); if (s == null) { // error case return null; } else if (s.length() == 0) { // base case permutations.add(""); return permutations; } char first = s.charAt(0); // get the first character String remainder = s.substring(1); // remove the first character ArrayList words = getPerms(remainder); for (String word : words) { for (int j = 0; j <= word.length(); j++) { permutations.add(insertCharAt(word, first, j)); } } return permutations; } public static String insertCharAt(String word, char c, int i) { String start = word.substring(0, i); String end = word.substring(i); System.out.println("start=" + start + "\t c=" + c + "\t end=" + end ); return start + c + end; } public static void main(String a[]) { ArrayList perm = new ArrayList(); perm=getPerms("abc"); //for(String ele:perm) //System.out.println(ele); } }Compile: javac Permutation.java
Run: java Permutation
/*output analysis
start= c=c end=
start= c=b end=c
start=c c=b end=
start= c=a end=bc
start=b c=a end=c
start=bc c=a end=
start= c=a end=cb
start=c c=a end=b
start=cb c=a end=
*/
@Shashank .. This is awesome solution , i was not aware of this , thanks for sharing
My solution:
#include<stdio.h> void printer(int *a,int n){ int i; for(i=0;i<n;i++)printf("%d",a[i]);printf("\n"); } /*recursive permute function Semantics: a - array which holds the present permutation of size n k - present slot in the array a. we have a permutation when k==n if k < n , we are still building our permutation. We can think of the permutation result as a row of n slots, holding a number between 1 and n (if we want permutations from another array b, we can think of it as holding b[1] to b[n] ..the logic is the same) if we don't want them to repeat, we need to maintain state of our computations in the array called 'selected'. */ void permute(int *a,int n,int k,int *selected){ if(k==n){ printer(a,n); return; } int i; for(i=0;i<n;i++){ if(!selected[i]){ a[k]=i+1; //alternately, a[k]=f(i) , here f(i)=i+1. //essentially, the i'th value from a list. selected[i]=1; permute(a,n,k+1,selected); //fill up from the next index selected[i]=0; //backtrack } } } int main(void){ int a[10]={0}; int i; int selected[10]={0}; permute(a,5,0,selected); return 0; }Advantages:
1. code is clear and the printer() function can be replaced by
a process() function which is 'streamed' one permutation at a time
2. It can also be used to permute values from a function.
we are just storing the indices.
3. Can be extended to print permutations with repetition:
make the if condition always evaluate to true
like (if(1 || !selected[i] ) ) ...
this is a really clean implementation, and i like that it lists in lexicographic order.
question: what if i had an application where i could reduce run time by avoiding some permutations...
like if i wanted to enumerate every other permutation, or only the first (n!)/2 permutations?
in particular, ive reached a case in a problem im solving where 1,2,3,4 is the effective equivalent of 4,3,2,1...
so i want to remove those from being evaluated; but im not sure how to group out such subsets...
This code is plagiarised from Programming interview exposed
I do not intend to Offend you ,but you should have mentioned the source of your code .
Just another improvement.
The function prototype can be just permute(char *a, int size);
Modification would be:
instead of swapping every element in loop with first element,
we can swap it with last element and call permute(a, size-1);
what do you say?
Hey,
how would do it for strings with repeated string
Hey,
how would do it for strings with repeated char
See this post to understand the logic behind printing all permutations without duplicates (even when duplicate characters are present in the input).
http://www.divye.in/2011/06/printing-all-permutations-of-string.html
I think this will work. I ran this and its working:
private void swap(ref char a, ref char b) { if (a == b) return; a ^= b; b ^= a; a ^= b; } private void go(char[] list, int k, int m) { int i; if (k == m) { Console.Write(list); Console.WriteLine(" "); } else for (i = k; i <= m; i++) { if (list[k] == list[i] && k != i) continue; swap(ref list[k], ref list[i]); go(list, k + 1, m); swap(ref list[k], ref list[i]); } }Only difference is in Swap function, So swap is also checking if swapping characters are equivalent.
copied well from stack overflow ....... nice!!
For the main code given on this page, I think for string = “aaa” it will print “aaa” several times instead of just once. To remove this error, do the following modification:
for (j = i; j <= n; j++) { if (A[i] == A[j] && i != j) continue; swap((a+i), (a+j)); permute(a, i+1, n); swap((a+i), (a+j)); //backtrack }The highlighted line is not preventing print of same "AAA". I think we need to check for same string and should not execute in case of same string.
For the main code given on this page, I think for string = "aaa" it will print "aaa" several times instead of just once. To remove this error, do the following modification:
for (j = i; j <= n; j++) { if (A[i] == A[j] && i != j) continue; swap((a+i), (a+j)); permute(a, i+1, n); swap((a+i), (a+j)); //backtrack }not working for string "agra"
output is --
agra
agar
arga
arag
aarg
aagr
gara
gaar
graa
rgaa
raga
raag
raag
raga
hw abt this:
rotate the given array n-1 times
then reverse the intial array and again rotate it n-1 times!
woud'nt it be better than using recursion?
It doesn't provide all solutions!!?
instead of n! permutations, it just gives 2n
correct me in case of misinterpretation
Would this work for 'N' number of characters in String?
here is my code, if anybody likes
#include<stdio.h> #include<string.h> void ror(char str1[],int a,int b) { char temp=str1[a]; int j; for(j=a;j<b;j++) { str1[j]=str1[j+1]; } str1[b]=temp; } void perm(char str[],int f,int l) { int i; char str1[5]; strcpy(str1,str); if(f==l) { printf("%s\t",str1); return; } for(i=f;i<=l;i++) { perm(str1,f+1,l); ror(str1,f,l); } } int main() { perm("vikas",0,4); getchar(); }@rscrbv
@geeksforgeek
..could plz tell me how ur code is working..plz help le out that how the control is tranferring..take string abc & plz show ur flow control at for every combination...i really need help in dis..program...reply asap.
@rscrbv
@geeksforgeek
..could plz tell me how ur code is working..take string abc & plz show ur flow control at for every combination…i really need help in dis..program…reply asap.
why does not any one explain this well-loved code
thanks!
well done
what will done when call Function permute(a, i+1, n);
for (j = i; j <= n; j++) { swap((a+i), (a+j)); permute(a, i+1, n); swap((a+i), (a+j)); //backtrack }Simple and non-recursive, lexically correct output.
std::string default = "Hallo"; int perm=1, digits=default.size(); for (int i=1;i<=digits;perm*=i++); for (int a=0;a<perm;a++) { std::string avail=default; for (int b=digits,div=perm;b>0; b--) { div/=b; int index = (a/div)%b; printf("%c", avail[index] ); avail.erase(index,1) ; } printf("\n"); } printf("permutations:%d\n",perm);(c) Sven Forstmann
@Sven Forstmann: Can you please write algorithm for the above code?
This code does not work for non-unique set of characters. But works for unique set of characters.
You are assuming the string contains no dup chars. However, your sample string has two 'l's. Your own sample doesn't work.
@amit: The diagram shows recursive execution of permute().
For i = 0 and j = 0
A is fixed at first place using below line
Then all the permutations of BC (sub-string after A) are printed
Finally swap the characters back
For i = 0 and j = 1
B is fixed at first place using below line
Then all the permutations of BC (sub-string after A) are printed
Finally, swap the characters back
For i = 0 and j = 2
C is fixed at first place using below line
Then all the permutations of BC (sub-string after A) are printed
Finally, swap the characters back
For i = 1, second character is swapped one by one with the other characters (after second character). Same way is continued for i = 2, 3..
@geeksforgeeks
can u explan how this code works.
The complete code is at :
http://techpuzzl.wordpress.com/2010/01/11/string-permutation/
Ok.
We can call this function like perm("",s) where s is the string which has to be permuted.
I am not sure how to highlight the code in the Comment Section. I hope the code is readable enough.
@Srinivas Iyengar: Could you add more colors to the code given below, please? What should be prefix and suffix for the first call of permute() in main()?
/*Similar Recursive Code for Permutation of a String keeping track of prefix and suffix*/ void permute(string prefix,string suffix) { /* We can print prefix here for generating power set and simply write return in the following if case.*/ if(suffix.size()==0) printf("%s \n", prefix); else for(int i=0;i < suffix.size();i++) permute( prefix+suffix[i], suffix.substr(0,i)+suffix. substr(i+1, suffix.size()) ); }