Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating combinations in c++

I have been searching a source code for generating combination 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 idea to generate 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, like 5 2 outputs 1 2, 1 3, etc.. I had difficulty in constructing the algorithm. It took me a month thinking about this.

like image 503
Keneth Adrian Avatar asked Feb 24 '12 12:02

Keneth Adrian


People also ask

How do you generate all possible combinations of an array?

Use Include-Exclude to Generate All Possible Combinations in Java. Similarly, we create an empty array and use the Pascal identity problem to generate all the possible combinations of an array. In this method, we consider the elements of the given array and recure using the two cases.

How do you generate all possible combinations of one list?

Add a Custom Column to and name it List1. Enter the formula =List1. Expand out the new List1 column and then Close & Load the query to a table. The table will have all the combinations of items from both lists and we saved on making a custom column in List1 and avoided using a merge query altogether!


1 Answers

A simple way using std::next_permutation:

#include <iostream> #include <algorithm> #include <vector>  int main() {     int n, r;     std::cin >> n;     std::cin >> r;      std::vector<bool> v(n);     std::fill(v.end() - r, v.end(), true);      do {         for (int i = 0; i < n; ++i) {             if (v[i]) {                 std::cout << (i + 1) << " ";             }         }         std::cout << "\n";     } while (std::next_permutation(v.begin(), v.end()));     return 0; } 

or a slight variation that outputs the results in an easier to follow order:

#include <iostream> #include <algorithm> #include <vector>  int main() {    int n, r;    std::cin >> n;    std::cin >> r;     std::vector<bool> v(n);    std::fill(v.begin(), v.begin() + r, true);     do {        for (int i = 0; i < n; ++i) {            if (v[i]) {                std::cout << (i + 1) << " ";            }        }        std::cout << "\n";    } while (std::prev_permutation(v.begin(), v.end()));    return 0; } 

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v. Hope this helps.

like image 175
mitchnull Avatar answered Oct 12 '22 23:10

mitchnull