Generate Ordered Subset of "k" elements from a set of "n" elements

Hello forum,


I have found in the STL algorithm; next_permutation(..) that i can generate the following permutation

of the elements {1,2,3} as:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1


But now i want to generate ordered subset of 2 elemnts from the above 3 elements as follows:


1 2
1 3
2 1
2 3
3 1
3 2

Any hint on that?


Regards
Sajjad
In the case where you are going from N elements to N-1 elements, you
can still use next_permutation, just chop off the right-most element.

In the general case of N to M, M < N-1, chop off the last (N-M) elements,
then insert the resulting tuple into a set. There will be a lot of duplicates
that you can ignore.
It goes to an infinite loop for elemnts of 24.

How to deal with that?


Sajjad
I don't understand your problem.

What do you mean by "for elements of 24"?

Hello


I have n = 24

and i want to generate ordered k(2) - subset from n.

The theory is at the following link:

http://mathworld.wolfram.com/Permutation.html


When i run it using the next_permutation, it really takes time to generate that


Regards
Sajjad
If all you want to do is generate k(2) and not k(n), then I suggest just using two for loops. For example:

1
2
3
4
5
6
int my_set[ 24 ] - { /* values here */ };

for( int first = 0; first < 24; ++first )
    for( int second = 0; second < 24; ++second )
        if( first != second )
            std::cout << '{' << my_set[ first ] << ',' << my_set[ second ] << '}' << std::endl;


Obviously if 2 is a runtime parameter as opposed to a constant, then you'd need a variable
number of nested for loops, which makes the problem a bit harder and requires more
coding.

Topic archived. No new replies allowed.