-2

Good night, what's the best way in C to count the number of possibilities of UNIQUE anagrams in a string with the maximum length of 256 without allows repetitions caused by same letters? The input would be just in uppercase and only alphabet letters are allowed, A-Z. I got stuck in the worst case of the program that got 26! a very large number that overflow even my double. I think I'm very lost here, I'm not so good in C. The program just need to shows the number of possibilities, not the anagram. Like:

LOL = 3

HOUSE = 120

OLD = 6

ABCDEFGHIJKLMNOPQRSTUVWXYZ = 403291461126605635584000000

Thank you guys very much... I tried a lot and failed in every single tried, I'm in distress with it. The way I got more closer of do it was in Pascal, but it also failed in some tests, and I can't use Pascal anyway. I'm using CodeBlocks on Windows that compiles with GCC.

Adriano rox
  • 173
  • 1
  • 8
  • 3
    We are not a "do my homework service"! Read [ask]. If you don't know C, get a good book and learn the language. But as that is an assignment, you might want to consult your course material and notes. – too honest for this site Jun 18 '17 at 22:46
  • I don't have a course material, i'm not at school. – Adriano rox Jun 18 '17 at 22:51
  • 1
    Shouldn't the title be number of "permutations", not number of "combinations"? For example, there are 3 unique permutations for "LOL", but only 1 combination. – rcgldr Jun 18 '17 at 22:57

1 Answers1

1

You should calculate factorial of the length of the given string divided by the factorial of the occurrence of every letter.

long double logFactorial (int i) {
    return i < 2 ? 0.L : (logFactorial (i-1)+log(long double (i));
}
int countLetter(const char* str, char c) {
    int res = 0;
    while (str && *str) {
        res += *str++ == c;
    }
    return res;
}
long double numPermutations(const char* str) {
    auto res = logFactorial (strlen(str));
    for (char c = 'A'; c<='Z'; c++) {
        res -= logFactorial (countLetter (str,c));
    }
    return exp((long double)res);
}

Pay attention!

There are several people here who were correct by saying that factorial of 26 cannot be stored even in 64bit integer.

Therefore, I changed my calculation to the logarithmic of the factorial number and store it in long double which I hope is precise enough (I think that the exp() function is not precise enough)

Nevertheless you cannot use this result as an integer value, unless you find a way to store it in 128bit integer or bigger... You should test it too if this fits your problem.

There is a faster way to calculate the factorial for this problem by storing the results of 0! up to 26! in an array of the size of [27].

I will leave it to you for asking another question.