有没有更有效的检查对的方法?

时间:2014-06-25 20:18:20

标签: c++

我正在制定一个可以解决问题的计划。卡片和检查是否有一对存在或同花顺。我很好奇是否有更有效的方法来检查任何两个元素是否匹配,而不是下面的代码。谢谢!

//checks if any card has value the same
    if (temp2 == (temp4 || temp6 || temp8 || temp10) || temp4 == (temp6 || temp8 || temp10) || temp6 == (temp8 || temp10) || temp8 == temp10){
        ++pairCount;
    }

//checks if card has all the same suit
    if (temp1 == temp3 == temp5 == temp7 == temp9){
        ++flushCount;
    }

5 个答案:

答案 0 :(得分:0)

如果您按照值对手进行排序,则可以仅针对相邻的卡进行检查。假设有类似的东西:

struct card
{
   int value;
   int suit;
};

struct card hand[5];

你可以这样做:

if (hand[0].value == hand[1].value ||
    hand[1].value == hand[2].value ||
    hand[2].value == hand[3].value ||
    hand[3].value == hand[4].value)

您当前的支票无论如何都不起作用 - temp2 == (temp4 || temp6 || temp8 || temp10)可能无法完成您的想法。你需要这样的东西:

if ((temp2 == temp4) || (temp2 == temp6) || (temp2 == temp8) || (temp2 == temp10))

temp2与其他每个变量进行比较。

答案 1 :(得分:0)

指针可以是卡号哈希映射的向量,即

vector<unsigned int> cardCounts;
cards.resize(13,0);
vector<Card> cards{getCards()};
for (const Card& c : cards) {
   ++cardCount[c.getNo()];
   switch(cardCount[c.getNo()]) {
       case 2:
          //deal with pair
       break;
       case 3:
           //deal with triple
       break;
       case 4:
           //deal with quad
       break;
   }
 }

你只需要小心,因为这段代码将执行dealWithPair(),然后执行dealWithTriple(),然后依赖于相同数量的卡的数量,依次执行dealWithQuads()。只要确保他们不会发生冲突

答案 2 :(得分:0)

  1. 将所有元素放在容器中:

    std::vector<Card> cards = /* ... */ ;
    
  2. 按顺序放置元素。

    sort(begin(cards), end(cards));
    
  3. 看看是否有重复的卡片:

    auto it = adjacent_find(begin(cards), end(cards));
    if (it != end(cards))
    {
        std::cout << "Card " << *it << " is repeated.\n";
    }
    else
    {
        std::cout << "No pairs\n";
    }
    
  4. 您至少需要<algorithm><iterator>以及其他一些标题。

答案 3 :(得分:0)

我使用这种方法来简化检查配对(不是很干净,因为复杂度为O(n²)!)

  bool check_pair(int *array){ //if you choose to pass -hand- as array of 5 integers

        for(int i=0;i<5;i++){ // 5: I suppose its a poker game
            for(int j=i+1;j<4;j++){
                if(array[i]==array[j]){
                    return true;
                }
            }
        }
        return false;
    }

答案 4 :(得分:-1)

如何将每张卡片写入地图,其中键是面部,值是它出现的次数?

具有值&#39; 2&#39;的地图元素的数量那就是你的对数,你可以免费得到你的三种和四种。

请注意,对于一张五张牌的牌,我不知道计算上每张牌与其他牌相比更有效率。

相关问题