c++ - all combinations of k elements out of n -


can provide me link or pseudocode of function finding combinations of k elements out of n? possibly in stl. don't need compute n choose k, need list vectors of numbers of size k.

thanks

in c++ given following routine:

template <typename iterator> inline bool next_combination(const iterator first, iterator k, const iterator last) {    /* credits: thomas draper */    if ((first == last) || (first == k) || (last == k))       return false;    iterator itr1 = first;    iterator itr2 = last;    ++itr1;    if (last == itr1)       return false;    itr1 = last;    --itr1;    itr1 = k;    --itr2;    while (first != itr1)    {       if (*--itr1 < *itr2)       {          iterator j = k;          while (!(*itr1 < *j)) ++j;          std::iter_swap(itr1,j);          ++itr1;          ++j;          itr2 = k;          std::rotate(itr1,j,last);          while (last != j)          {             ++j;             ++itr2;          }          std::rotate(k,itr2,last);          return true;       }    }    std::rotate(first,k,last);    return false; } 

you can proceed following:

// 9-choose-3  std::string s = "123456789"; std::size_t k = 3; {    std::cout << std::string(s.begin(),s.begin() + k) << std::endl; } while(next_combination(s.begin(),s.begin() + k,s.end())); 

or std::vector of int's:

// 5-choose-3  std::size_t n = 5; std::size_t k = 3;  std::vector<int> ints; (int = 0; < n; ints.push_back(i++));  {    (int = 0; < k; ++i)    {       std::cout << ints[i];    }    std::cout << "\n"; } while(next_combination(ints.begin(),ints.begin() + k,ints.end())); 

Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -