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:
A
AB
ABC
AC
ACB
B
BA
BAC
BC
BCA
C
CA
CAB
CB
CBA
You need to keep track of
- How many characters you have chosen, which, and in which order: and
int
and achar[]
- How many characters you may still choose and which: an
int
and 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) {int i; for(i = 0; *string_left > 0 && i < pool_length; ++i) { if (pool[i] may be picked) { // 1. pick that as the num_picked + 1st character // 2. output and decrement *strings_left // 3. recur // 4. unpick pool[i] } }
}
I hope that helps and I haven’t given too much away.
solved Complex C program [closed]