C code to generate all strings of length upto k on a given set of symbols. No symbol should be repeated in any string.
Example:
Take the 6 lower-case symbols in the English alphabet {a, b, c, d, e, f} and k = 3; print the first 25 strings of your output sorted in dictionary order.
Can anyone help me out please?
EDIT
# include <stdio.h>
# include <conio.h>
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j <= n; j++)
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j));
}
}
}
int main()
{
char a[] = "ABC";
permute(a, 0, 2);
getchar();
return 0;
}
This however will give the permutations of all the alphabets. Replacing the alphabets to be parametrized by blank space doesn’t seem to do the trick!
Even repetedly calling permute with permutable blank spaces doesnt sound efficient.
Assuming your pool of characters is sorted and without repetitions (may need some preprocessing), generating the desired strings in lexicographic order is automatic (in the approach I have in mind).
Look at the short example of all nonempty strings that can be generated from “ABC” with the restrictions:
You need to keep track of
intand achar[]intand abool[](orchar[],int[])How many strings you still need to output, since that will be modified in recursive calls: an
int*void permute(char *pool, int pool_length, int num_picked, char *stringy,
bool *picked, int max_length, int *strings_left) {
}
I hope that helps and I haven’t given too much away.