Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all the combinations of a number in C++

Tags:

c++

algorithm

I need to get all the possible combinations of a given set. For example, given: [1, 4, 7], the resulting combinations should be:

  • 111, 114, 117, 141, 144, 147, 171, 174, 177, 411, 414, 417, 441, 444, 447, 471, 474, 477, 711, 714, 717, 741, 744, 747, 771, 774, 777.

I tried using next_permutation method, but it isn't what I want (this does not return values like 111, 144, 717, etc).

So is there any way I can do this in C++? Please note that I'm a complete beginner.

Thanks in advance.

like image 236
Roshnal Avatar asked Dec 28 '22 01:12

Roshnal


1 Answers

Have a hard look at the numbers: All numbers you listed can also be expressed as the list {11,14,17,41,44,47,71,74,77} prefixed once with 1, once with 4 and once with 7. This points to a generic rule:

The strings with 3 numbers of the set {1,4,7} are built by taking the strings with 2 numbers of the same set and prepending each element of the set.

Generalize the 3 and 2 in this rule, implement the resulting idea with recursion, and you have an algorithm for your problem.

As a C++ implementation note, make sure that you use strings instead of integers to represent your numbers. This problem is not arithmetic, and tightly coupled to the base-10 representation. Strings will make your life much easier.

like image 157
thiton Avatar answered Dec 29 '22 15:12

thiton