Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

cartesian product - Creating all possible combinations by taking k no: of items from an array with n no: of items in C++

I'm looking for a way to insert an array with length n and get all possible combinations with length k. The elements can repeat.

If the no: of elements in the array = n and the sample size = k, the no: of possible combinations should be (n)^k.


For example if the array is [a,b,c] and k=2, then the possible combinations should be aa,ab,ac,bb,ba,bc,cc,ca,cb. The no: of combinations will be (3)^2=9


  1. How do I create a dynamic array with the function std::vector
  2. How do I get all the possible combinations?

I'm new to programming and hope you can explain a bit. Thanks in advance!

question from:https://stackoverflow.com/questions/65931570/creating-all-possible-combinations-by-taking-k-no-of-items-from-an-array-with-n

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A hard code solution would be:

for (int a1 : v) {
  for (int a2 : v) {
    for (int a3 : v) {
      for (int a4 : v) {
        for (int a5 : v) {
            do_job(a1, a2, a3, a4, a5);
        }
      }
    }
  }
}

You may use the following for a generic way (putting all as into vector):

bool increase(std::size_t n, std::vector<std::size_t>& its)
{
    for (auto rit = its.rbegin(); rit != its.rend(); ++rit) {
        ++*rit;
        if (*rit >= n) {
            *rit = 0;
        } else {
            return true;
        }
    }
    return false;
}

template <typename F, typename C>
void iterate(F f, const C& v, std::size_t k)
{
    std::vector<std::size_t> it(k, 0);
 
    do {
        f(v, it);
    } while (increase(v.size(), it));
}

Live Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...