I am having difficulty implementing an "n choose k" function in C/C++. It seems like it is a recursive function, but mine is buggy for k greater than two.

The function should have parameters like:

nchoosek(int k, int n, int *in, int *out)

where "in" as an array of ints of length n and "out" is the resulting array of length [n!/k!*(n-k)!] *k.

For example, let in=[0 1 2 3] n=4 k=3, then

out=[0 1 2 0 1 3 0 2 3 1 2 3]

I am getting tired of fixing mine!

Thanks,

Dan

The function should have parameters like:

nchoosek(int k, int n, int *in, int *out)

where "in" as an array of ints of length n and "out" is the resulting array of length [n!/k!*(n-k)!] *k.

For example, let in=[0 1 2 3] n=4 k=3, then

out=[0 1 2 0 1 3 0 2 3 1 2 3]

I am getting tired of fixing mine!

Thanks,

Dan

void nchoosek(int k, int n, int *in, int **out, int * numberelem)

{

/* Your code */

/* Setup return array */

*out = (int *)malloc( sizeof(int) * number_of_elements ) ;

/* Setup return value for number of elements */

*numberelem = number_of_elements ;

/* Your code */

}

Call with

int * out ;

int in[] = { 0, 1, 2, 3 } ;

int number ;

nchoosek( 3, 4, &in, &out, &number ) ;

number will now contains the number of elements

out will contain the returned array, you can reference using out[0], out[1], etc.

When done with "out" in your main code do free(out) ;

That should be enough to get you started.

Remember if recursive your calling code can go inside nchoosek.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.