# How can I iterate throught every possible combination of n playing cards

How can I loop through all combinations of n playing cards in a standard deck of 52 cards?

-
What have you tried so far? –  Oliver Charlesworth Feb 22 '11 at 10:09
Google binomial coefficient or combinations.... –  Tony The Lion Feb 22 '11 at 10:15
@Oli Charleswoth: I can do it with two cards paste.ubuntu.com/570512 –  tm1rbrt Feb 22 '11 at 10:57
To make it work with more than 2 (n times), you'll have to turn the inner loop into a recursive function call. Also just start the loop from `i + 1`. –  visitor Feb 22 '11 at 11:55

You need all combinations of `n` items from a set of `N` items (in your case, `N == 52`, but I'll keep the answer generic).

Each combination can be represented as an array of item indexes, `size_t item[n]`, such that:

• `0 <= item[i] < N`
• `item[i] < item[i+1]`, so that each combination is a unique subset.

Start with `item[i] = i`. Then to iterate to the next combination:

• If the final index can be incremented (i.e. `item[n-1] < N-1`), then do that.
• Otherwise, work backwards until you find an index that can be incremented, and still leave room for all the following indexes (i.e. `item[n-i] < N-i`). Increment that, then reset all the following indexes to the smallest possible values.
• If you can't find any index that you can increment (i.e. `item[0] == N-n`), then you're done.

In code, it might look something vaguely like this (untested):

``````void first_combination(size_t item[], size_t n)
{
for (size_t i = 0; i < n; ++i) {
item[i] = i;
}
}

bool next_combination(size_t item[], size_t n, size_t N)
{
for (size_t i = 1; i <= n; ++i) {
if (item[n-i] < N-i) {
++item[n-i];
for (size_t j = n-i+1; j < n; ++j) {
item[j] = item[j-1] + 1;
}
return true;
}
}
return false;
}
``````

It might be nice to make it more generic, and to look more like `std::next_permutation`, but that's the general idea.

-

I see this problem is essentially the same as the power set problem. Please see Problems with writing powerset code to get an elegant solution.

-
Powerset enumerates all subsets of any size. But this wants subsets only of size n. This is a combinations problem, not a powerset problem. –  Raymond Chen Aug 26 '13 at 22:17
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}