Re: permutations and STL containers
On Nov 1, 8:58 am, mpho <tjab...@gmail.com> wrote:
hello,
I have a q-tuple {X_1, X_2, ... , X_q} where each X_i$B!!(Bcan take only 2
values. Thus there will be 2^q (2 exponent q) q-tuples. I'd like to
create a list of all these 2^q permutations using an STL container
list; or perhaps array of vectors. Can anyone show me an efficient way
to do this.
I think using std::next_permutation() would solve your problem. Here
is an example program to get you started.
$ cat combi.cc
#include <algorithm>
#include <iostream>
#include <vector>
#include <iterator>
enum V { A = 2, B = 8 }; // The two values
void init_vector(std::vector<V>& mis, int num) {
// The value 'num' provides number of elements
// that have first value ('A').
size_t M = mis.size();
for(size_t i = 0; i < M; ++i) {
(i < num)
? (mis[i] = A)
: (mis[i] = B);
}
}
int main() {
int combi = 0;
std::vector<V> sp(4);
size_t M = sp.size();
std::ostream_iterator<V> Iter(std::cout);
for(size_t i = 0; i <= M; ++i) {
init_vector(sp, i);
std::copy(sp.begin(), sp.end(), Iter);
++combi;
std::cout << std::endl;
while (std::next_permutation(sp.begin(), sp.end()))
{
std::copy(sp.begin(), sp.end(), Iter);
++combi;
std::cout << std::endl;
}
}
std::cout << "Total permutations: " << combi << std::endl;
}
$ g++ combi.cc
$ ./a.exe
8888
2888
8288
8828
8882
2288
2828
2882
8228
8282
8822
2228
2282
2822
8222
2222
Total permutations: 16
$
Rgds,
anna
--
Naked at USA Airports
http://tinyurl.com/usa-airport-naked
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]