Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A permutation of a set is a list of all possible arrangements of items in the se

ID: 3817360 • Letter: A

Question

A permutation of a set is a list of all possible arrangements of items in the set where the order is important. For example, the permutation of the set {a b c} is (a b c), (a c b), (b a c), (b c a), (c a b), (c b a). A set with n elements has n! permutations. Write a recursive program that prompts a user to enter words until the word GO is entered. Then print all permutations of those words.

For example:

Enter a word: many

Enter a word: dogs

Enter a word: jump

Enter a word: GO

many dogs jump

many jump dogs ….

Hint: Here is an example of a recursive algorithm for computing permutations of the set {a b c d}.

Print a, followed by all permutations of {b c d}

Print b, followed by all permutations of {a c d}

Print c, followed by all permutations of {a b d}

Print d, followed by all permutations of {a b c}

Explanation / Answer

#include <stdio.h>
#include <string.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 l, int r)
{
int i;
if (l == r)
printf("%s ", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}

int main()
{
char str[100];
printf("Enter a word: ");
scanf("%s", str);
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote