D
D
dearname2014-04-12 18:17:40
C++ / C#
dearname, 2014-04-12 18:17:40

Binary vector permutations

Good evening, I need to output all permutations of a vector of a certain length and a certain weight. Here is how I implemented.

#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;

vector<int> generator(int n, int m) {
    vector <int> v;
    for(int i=0; i<pow(2,n)-1; i++ ) {
        if(i<=m-1)  v.push_back(1);
        else v.push_back(0);
    }
return v;
}

int main()
    {
        int n,m;
        cout<<"N:";
        cin>>n;
        cout<<"M:";
        cin>>m;
        vector<int> v = generator(n,m);

        do
        {
             for(int i=0; i<v.size(); i++)
                cout <<v[i]<<" ";
             cout<<endl;
        }
        while(next_permutation(v.begin(), v.end()));
        return 0;
    }

But for some reason it doesn't work, I can't figure out why. Outputs only at the beginning the vector that was created, and then does not display anything, exits. It turns out one permutation or something.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Belov, 2014-04-12
@dearname

Pushkin will sort?)

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

using namespace std;

vector<int> generator(int n, int m) {
    vector <int> v;
    for(int i=0; i<pow((double)2,n)-1; i++ ) {
        if(i<=m-1)  v.push_back(1);
        else v.push_back(0);
    }
return v;
}

int main()
    {
        int n,m;
        cout<<"N:";
        cin>>n;
        cout<<"M:";
        cin>>m;
        vector<int> v = generator(n,m);
  sort(v.begin(), v.end());
        do
        {
             for(int i=0; i<v.size(); i++)
                cout <<v[i]<<" ";
             cout<<endl;
        }
        while(next_permutation(v.begin(), v.end()));
        return 0;
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question