EDIT: I meant Permutations, not combinations. Thanks.
I realize this is a rather open ended question, and I'm not looking for code per say, but really some hints where to start. What I want to make is a program, that can generate every combination of characters for a given length, i.e the user inputs 4, and the program will generate every possible combination of ASCII characters for a length of 4.
Not really sure where I would start, perhaps the use of a hash table? Of course loops will be needed but I'm unsure how to design them to produce combinations. Up until now, its always been a case of, loop until 1000 things have happened for example.
Any advice is much appreciated !
Cheers,
T.
Yeah, this pretty much calls for a recursive solution. To generate all N-length words, the basic algorithm is
If all you need to do is print these strings out to a file or something as you generate them, then you don't need any kind of complicated data structure. All you need is a single buffer to hold the generated word.
Important question: are you sure you want every possible combination of all ASCII characters (including punctuation, control characters, etc.)? Or all possible combinations of alhphanumeric strings? Or strictly alphabetic strings?
You might want to specify your alphabet in your code, like
and just index into that instead of assuming a particular character representation:
For permutations, you can use a recursive solution like this (which can probably be optimised and improved):
Note that the output of this function (no matter how you implement it) is 26n, which is 456,976 when n (the input for this function) is 4.
Here's a complete and working solution I just converted to C++ from the documentation of the python method itertools.permutations. http://docs.python.org/library/itertools.html#itertools.permutations . In the original python form it's a generator (just think iterator) but I did not bother with that now although it would make a lot of sense.
The permutations method is a template so this works with any object you can store in a vector, not just char. With this code:
the result is a vector of 'vector' representing all the non-repeating 3-combinations of abcd:
Here's the code (C++11):
As a note:
The alphabet is not checked to be unique, instead the permutations and selections are done by index so if you want to allow for more than one of an object just add more of it to the alphabet. The contents need also not be comparable.
Your question is too general. Any how, you could use the trie data structure to get what you want. But if you are going to do it in c it would still require a lot of work. I would suggest use a language where in you don't have to recreate the wheel.