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

Is there a more efficient way of checking pairs?

本文关键字:方法 检查 有效 有没有      更新时间:2023-10-16

我正在编写一个程序,该程序分发"手牌"并检查是否有一对或同花顺。我很好奇是否有一种比下面的代码更有效的方法来检查任何两个元素是否匹配。谢谢你!

//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;
    }

如果将手牌按值排序,则可以仅对照相邻的牌进行检查。假设如下:

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和其他变量

手可以是与卡号hashmap等价的向量,即

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(),一个接一个地执行,这取决于相同数量的卡牌的数量。只要确保它们不冲突

  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 pairsn";
    }
    

您将需要至少<algorithm><iterator>,以及一些其他标题

我使用这种方法是为了简单地检查pair(不是很干净,因为复杂度为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;
    }

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

值为"2"的map元素的数目就是你的配对数目,你可以免费得到你的"三种"answers"四种"。

请注意,对于一张五张牌的手牌,我不知道它会比每一张牌与其他牌进行对比计算更有效率。