Wednesday, August 15, 2012

C Program : Rank of a word

Rank of a word is the position of the word when all the permutations of the letters in the word are listed in dictionary order. So for example "cat" is the word, then, various permutations in dictionary order are-
1. act
2. atc
3. cat
4. cta
5. tac
6. tca
Hence the rank of "cat" is 3.
Here is the logic in short-
Sort the word, find number of permutations that can be formed with letters which come before ith letter in original word.
So for i = 0, ith letter is 'c' and the sorted word is "act", so we need to find all permutations starting with 'a' and so on.

Below is the program that takes care of duplicates as well.

#include <stdio.h>
#include <string.h>

long fact(int n)
{
long f = 1;
while (n > 0)
{
f *= n;
n--;
}
return f;
}

int find_rank(char s[], int len)
{
long rank = 1;
int i, j, k, l, fr[26], f; //fr is frequency
char sorted[100], cur, t, pre;

for (i = 0; i < len -1 ; ++i)
{
cur = s[i];
strcpy(sorted, s + i);
l = len - i;
memset(fr, 0, sizeof(fr));
fr[sorted[0] - 'a']++;
for (j = 1; j < l; ++j)
{
t = sorted[j];
fr[t-'a']++;
for (k = j-1; k >=0 && sorted[k] > t; --k)
sorted[k+1] = sorted[k];
sorted[k+1] = t;
}
pre = 1;
for (k = 0; sorted[k] != cur ;++k)
{
if (sorted[k] == pre)
continue;
pre = sorted[k];

f = fact(l - 1);
fr[pre - 'a']--;
for (j = 0; j < 26; ++j)
if (fr[j])
f /= fact(fr[j]);
rank += f;
fr[pre - 'a']++;
}
}
return rank;
}

int main()
{
char s[100];

scanf("%s", s);
printf("%d", find_rank(s, strlen(s)));
return 0;
}

No comments:

Post a Comment