c++ - Calculate Combination based on position -


i have combinations this:

1,2,3,4 //index 0
1,2,3,5 //index 1
1,2,3,6 //index 2

and on until 7,8,9,10

so n=10 k=4 combinatorics

how calculate combination index

for example when index==1
mycmb = func(index)
returns 1,2,3,5

this example need bigest numbers, , more params , without (if possible) many loops

i find obtain position: http://answers.yahoo.com/question/index?qid=20110320070039aa045ib

i want reverse this...

i programming in c++ sugesstions or help

it seems want find k-combination given number.

following example, here's should work:

#include <cstddef> #include <iostream> #include <string> #include <boost/lexical_cast.hpp> #include <boost/math/special_functions/binomial.hpp>   std::size_t choose(double n, double k) {   using boost::math::binomial_coefficient;   if (n < k) return 0;   return static_cast<std::size_t>(binomial_coefficient<double>(n, k)); }  // returns largest n such choose(n, k) <= pos. int combinationelement(int k, int pos) {   int n = k;   int coeff = 1, prev_coeff = 0;    while (coeff <= pos) {     coeff = choose(++n, k);     prev_coeff = coeff;   }    return n - 1; }  // returns k-combination @ position pos. std::vector<int> combination(int k, int pos) {   std::vector<int> combination;   (; k > 0; --k) {     int n = combinationelement(k, pos);     combination.push_back(n);     pos -= choose(n, k);   }   return combination; }  int main(int argc, char** argv) {   using std::cout;   using std::endl;    if (argc != 3) {     cout << "usage:  $ " << argv[0] << " k pos" << endl;     cout << "prints k-combination @ position pos." << endl;     return 1;   }    int k = boost::lexical_cast<int>(argv[1]);   int pos = boost::lexical_cast<int>(argv[2]);    std::vector<int> combination = combination(k, pos);    (int = 0; < k; i++)     cout << combination[i] << " ";   cout << std::endl; } 

note, convenience, code depends on boost calculate binomial coefficients (boost::math::binomial_coefficient<t>), , parse strings integers (boost::lexical_cast).


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -