I have an array of n elements, I need to put all 2- combination of them into arrays of length 2. for example:
suppose comb is a 2 dimensional array.
n = 1,2,3
I need to put all 2- combinations to comb[i][j] like that:
comb[0][0] = {1}
comb[0][1] = {2}
comb[1][0] = {1}
comb[1][1] = {3}
comb[2][0] = {2}
comb[2][1] = {3}
I do not know how to write the code!
Thanks
My Answer:
The O(n!) answer: n = total number m= total possible answer
int m = 0;
for (int i = 0; i < n - 1; i++){
int first = a[i];
for(int j = i+1 ; j < n ; j++){
int second = a[j];
comb[m][0] = first;
comb[m][1] = second;
++m;
}
}
One easy way is using the
next_permutationfunction available in the STL library in order to generate all the possible permutations of your numbers, and then pick the first two elements of each one. Note that the sequence must be first sorted, as if not the previous permutations will be skipped.Remember that you must
#include <algorithm>to use this function.