I want to select 5 points set from n given points one by one exhaustively. In other words i want to do nC5 in c++ but not getting a simple way to do it. Please tell me any solution.

Recommended Answers

All 2 Replies

I haven't the slightest idea what you are talking about.

If I read this correctly, you are wanting to choose (with replacement) r items (points in this case) from a set of n items? This can be done easily using a vector to hold the sets:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[]){
    int n = 13, r = 7;
    cout <<  n << "C" << r << " of integer set 0 to 12:" << endl;
    vector<int> inputset, outputset;
    for( int i=0; i<n; i++ )
        inputset.push_back(i);
    cout << "input set: ";
    for( int i=0; i<(int)inputset.size(); i++ )
        cout << inputset[i] << " ";
    cout << endl;
    for( int i=0; i<r; i++ )
        outputset.push_back( inputset[rand()%n] )
    cout << "output set: ";
    for( int i=0; i<(int)outputset.size(); i++ )
        cout << outputset[i] << " ";
    cout << endl;
    return 0;
}

Doing nPr (randomly pick without replacement) is not much harder:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[]){
    int n = 13, r = 7;
    cout <<  n << "C" << r << " of integer set 0 to 12:" << endl;
    vector<int> inputset, outputset;
    for( int i=0; i<n; i++ )
        inputset.push_back(i);
    cout << "input set: ";
    for( int i=0; i<(int)inputset.size(); i++ )
        cout << inputset[i] << " ";
    cout << endl;
    random_shuffle( inputset.begin(), inputset.end() );
    outputset = vector<int>( inputset.begin(), inputset.begin() + r );
    cout << "output set: ";
    for( int i=0; i<r; i++ )
        cout << outputset[i] << " ";
    cout << endl;
    return 0;
}

If the set of inputs is very large, shuffling is not a good method. In this case you would want to construct your set using a list or deque which would allow you to remove a randomly selected item from the list in constant time. Of course, indexing to the randomly selected value takes linear time.... But you wanted something easy to implement, so there you go.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.