Friday, September 11, 2020

Printing all permutations of a string

You can use the following C code to print all two character permutations (with repetition allowed) of a string:

If you would like to print three character permutations, you have to add another for loop:

As you can see, this is not generalizable because you have to keep adding or deleting for loops manually. Also notice that with each loop, the p[] index is increased by one. We could use this fact to write a recursive function that could handle all character permutations:

This is a nice example of first writing the simple cases, seeing a pattern and reaching the general case, i.e. inductive reasoning.

No comments:

Post a Comment