How can I loop through all combinations of n playing cards in a standard deck of 52 cards?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
You need all combinations of
n
items from a set ofN
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: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.This combinations iterator class is derived from the previous answers posted here.
I did some benchmarks and it is a least 3x faster than any next_combination() function you would have used before.
I wrote the code in MetaTrader mql4 to do testing of triangular arbitrage trading in forex. I think you can port it easily to Java or C++.
Output:
Output:
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.