Write the code for producing/printing permutations of the characters in a string. For example: If "abc" is the input string, output permutations should be "abc", "bac", "bca", "acb", "cab", "cba". Click for Solution |
-
Warning: Illegal string offset 'name' in /home/prepdo6/gpl4you/discussquessub.php on line 681
A # 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);
return 0;
}
Warning: Illegal string offset 'name' in /home/prepdo6/gpl4you/discussquessub.php on line 681
A For i=0 to N
1. Swap letters 0 and i.
2. Permute letters 1 to N-1, printing or saving the entire string each time.
Permute(char* inputStart, char* current)
{
char *swap;
char temp;
if(*(current + 1) = '\0')
printf("%s\n", inputStart);
else
{
for(swap = current; *swap != '\0'; ++swap)
{
temp = *swap;
*swap = *current;
*current = temp;
Permute(inputStart, current + 1);
//revert the letters
*current = *swap;
*swap = temp;
}
}
}
Explore
- GPL4you
- Home
- Prepdoor - Online Mock Test
- About
- FAQs
- Contact
- Contact Us
© 2011 - gpl4you | All Rights Reserved.