I'm working on a project right now where I'm wanting to generate every possible string up to N characters in length. (It's for a useful purpose, not just some random whim. And no, it's not homework of any sort.)
So the way I've decided to do this is by creating a series of nested for loops, one for every character of the string. The problem is that I would have to create the same number of for loops as there are characters in the string, but I want the number of characters to be dynamic.
I strongly doubt that C++ allows any sort of run-time code generation that would make something like this easy, so I'm kind of at a stalemate. Can anyone give me some ideas on how to do this?
There are certainly many ways to do it. Here is my way to do it. The idea is simple: How do we count?
1,2,3,...,9,
When we reach 9, we flip the last digit to zero and insert the smallest possible digit in front.
That is precisely what the function Increment() in the below code does: it increments the last char if it can. If it can't, Increment() "flips" the last char back and proceeds to the second to last digit, and so on.
The advantage of my approach is that it could save the careless user from calling a too large combinatorial problem.
Just a note on the number of strings:
If you have N letters to choose from, and your strings are of length k, then you have N^k different strings. If you look at all strings of length k or less, then their number is of course
1+N+N^2+...+N^k = (N^(k+1)-1)/(N-1)
if we count the empty string and one less otherwise: