How can I loop through all combinations of n playing cards in a standard deck of 52 cards?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You need all combinations of
nitems from a set ofNitems (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] < Nitem[i] < item[i+1], so that each combination is a unique subset.Start with
item[i] = i. Then to iterate to the next combination:item[n-1] < N-1), then do that.item[n-i] < N-i). Increment that, then reset all the following indexes to the smallest possible values.item[0] == N-n), then you’re done.In code, it might look something vaguely like this (untested):
It might be nice to make it more generic, and to look more like
std::next_permutation, but that’s the general idea.