How can I iterate through every possible combination of n playing cards

前端 未结 4 1250
别那么骄傲
别那么骄傲 2020-12-04 02:56

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

4条回答
  •  一生所求
    2020-12-04 03:38

    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++.

    class CombinationsIterator
    {
    private:
    	int input_array[];
    	int index_array[];
    	int m_indices;      // K
    	int m_elements;     // N
    
    public:
    	CombinationsIterator(int &src_data[], int k)
    	{
    		m_indices = k;
    		m_elements = ArraySize(src_data);
    		ArrayCopy(input_array, src_data);
    		ArrayResize(index_array, m_indices);
    
    		// create initial combination (0..k-1)
    		for (int i = 0; i < m_indices; i++)
    		{
    			index_array[i] = i;
    		}
    	}
    
    	// https://stackoverflow.com/questions/5076695
    	// bool next_combination(int &item[], int k, int N)
    	bool advance()
    	{
    		int N = m_elements;
    		for (int i = m_indices - 1; i >= 0; --i)
    		{
    			if (index_array[i] < --N)
    			{
    				++index_array[i];
    				for (int j = i + 1; j < m_indices; ++j)
    				{
    					index_array[j] = index_array[j - 1] + 1;
    				}
    				return true;
    			}
    		}
    		return false;
    	}
    
    	void get(int &items[])
    	{
    		// fill items[] from input array
    		for (int i = 0; i < m_indices; i++)
    		{
    			items[i] = input_array[index_array[i]];
    		}
    	}
    };
    
    //+------------------------------------------------------------------+
    //|                                                                  |
    //+------------------------------------------------------------------+
    // driver program to test above class
    
    #define N 5
    #define K 3
    
    void OnStart()
    {
    	int x[N] = {1, 2, 3, 4, 5};
    
    	CombinationsIterator comboIt(x, K);
    
    	int items[K];
    
    	do
    	{
    		comboIt.get(items);
    
    		printf("%s", ArrayToString(items));
    
    	} while (comboIt.advance());
    
    }

    Output:

    1 2 3 
    1 2 4 
    1 2 5 
    1 3 4 
    1 3 5 
    1 4 5 
    2 3 4 
    2 3 5 
    2 4 5 
    3 4 5

提交回复
热议问题