Optimizing Permutation Algorithm
I was wondering if anybody could help me optimize my algorithm that calculates permutations of specified length, using a specified character set. I've tested it and it works for everything I've tried, including different character sets, and different min/max lengths (provided max > min and both nonzero).
Code:
int permutation (char **res, char *chrset, int min_len, int max_len)
{
char *tmp;
int pow_count, pos, set_len, count, permc, perm_per_len, size_set, wordlen;
count = 0;
size_set = 0;
while (chrset[size_set])
size_set++;
for (set_len = min_len; set_len <= max_len; set_len++) {
perm_per_len = 1;
pow_count = set_len;
while (pow_count--) {
perm_per_len *= size_set;
}
count += perm_per_len;
for (pow_count = 0; pow_count < perm_per_len; pow_count++) {
permc = 1;
tmp = *res++;
for (wordlen = 0; wordlen < set_len; wordlen++) {
pos = (pow_count / permc) % size_set;
*tmp++ = chrset[pos];
permc *= size_set;
}
}
}
return count;
}
Although it functions correctly, there is most likely a way that I'm missing that could be used to optimize it. For example, the inner loop calculates the value of "permc" every time it is run.