I have a problem for a university lab;
Write a short program that outputs all possible strings formed by using characters ‘c’, ‘a’, ‘r’, ‘b’, ‘o’, and ‘n’ exactly once.
It seems to be a common interview question and well documented.
So I’ve coded it with Java using a recursive method which wasn’t too hard, when or why would you choose not to use recursion and what would be the easiest way of doing it?
I started to code a counter that would count down on base 6, the output would then reference char’s and print the string.
Thanks,
Yes, there are plenty of times I would not use recursion. Recursion is not free, it has a cost in stack space and that can often be a much more limited resource than some others. There’s also a time cost, however small, in setting up and tearing down stack frames.
By way of example, the much vaunted factorial function is one where I would probably opt for an iterative approach where the numbers were large. Calculating 10000! with the Python:
will attempt to use a whopping 10,000 stack frames (though Python will protect you against this). The equivalent iterative solution:
will use just the one stack frame and precious little else.
It’s true that recursive solutions are often more elegant code but you have to temper that with the limitations of your environment.
Your
carbonexample is one where I would actually use recursion since:For example the following Python code does the trick:
producing:
Of course, if your string can be 10K long, I’d rethink it, since that would involve a lot more stack levels but, provided you keep in low enough, recursion is a viable solution.