Saturday, January 12, 2013

Simple Way to Generate All possible Combination in C++

Source Code Start:



#include <set>
#include <map>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <sstream>
#include <iostream>
#include <algorithm>


using namespace std;

int main()
{
    int n ;
    /*  n is number of items you want in combination operation
    /*  result shows bit representation where 1 is selected item
    /*  , 0 is not selected item.                                                 */
    cin >> n;
    for( int i = 0 ; i < (1<<n) ; ++i)
    {
        for(int j = 0 ; j < n ; ++j)
        {
            if( (i&(1<<j)) != 0 )
                cout << "1";
            else
                cout << "0";
        }
        cout << endl;
    }
    return 0;
}

Source Code End:

Sort an Array of Structure in C++

Sample Code's start


#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

struct sust
{
    int x , y;
};
sust array[100];


bool comp(sust x , sust y)
{
    if(x.x == y.x)
    {
        return x.y > y.y;
    }
    return x.x < y.x;
}

int main()
{
    int n = 10;
    for(int i = 0; i < 10; ++i)
    {
        array[i].x = 10;
        array[i].y = i+10;
    }

    sort(array, array+n, comp);

    for(int i = 0; i < 10; ++i)
    {
        cout << array[i].x << " " << array[i].y << endl;
    }

    return 0;
}

Sample Code's End


This sample code sort an array of structure according some condition in comp function where we see we write code for sort the structure variable in array ascending order of x values when x is same then you must sort in descending order.