I am solving this challenge : https://www.hackerrank.com/challenges/permutations-of-strings/problem
I am using this algorithm : https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
Suppose I enter my array of strings as {"a", "b", "c"}
, then the output should be :
a b c
a c b
b c a
c b a
b a c
c a b
Since there are 3 distinct strings, there are 3! = 6 permutations.
The program is also supposed to handle duplicate cases, so if I enter {"a", "b", "b"}
, there will only be 3! / 2! = 3 permutations.
Anyways when my program reaches c b a
then it quits. Why? How can I fix that?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char** s1, char** s2) // to swap two strings
{
char* temp = *s1;
*s1 = *s2;
*s2 = temp;
}
int next_permutation(int n, char **s)
{
/**
* Complete this method
* Return 0 when there is no next permutation and 1 otherwise
* Modify array s to its next permutation
*/
int k, i, l;
k = i = l = 0;
for(i = n - 2; i >= 0; i--) // first step
if(strcmp(s[i], s[i + 1]) < 0) {
k = i;
break;
}
if(i == -1)
return 0;
for(i = n - 1; i >= k + 1; i--) // second step
if(strcmp(s[k], s[i]) < 0) {
l = i;
break;
}
swap(&s[k], &s[l]); // third step
for(i = k + 1; i < n / 2; i++) // fourth step
swap(&s[i], &s[n - i - 1]);
return 1;
}
int main() // locked code
{
char **s;
int n;
scanf("%d", &n);
s = calloc(n, sizeof(char*));
for (int i = 0; i < n; i++)
{
s[i] = calloc(11, sizeof(char));
scanf("%s", s[i]);
}
do
{
for (int i = 0; i < n; i++)
printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
} while (next_permutation(n, s));
for (int i = 0; i < n; i++)
free(s[i]);
free(s);
return 0;
}