I have been searching for a source code for generating combinations using C++. I found some advanced codes for this but that is good for only specific number predefined data. Can anyone give me some hints, or perhaps, some ideas to generate a combination?
As an example, suppose the set S = { 1, 2, 3, ...., n} and we pick r= 2 out of it. The input would be n and r. In this case, the program will generate arrays of length two. So input of 5 2 would output 1 2, 1 3.
I had difficulty in constructing the algorithm. It took me a month to think about this.
A simple way using
std::next_permutation:or a slight variation that outputs the results in an easier to follow order:
A bit of explanation:
It works by creating a "selection array" (
v), where we placerselectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation ofv.