有没有更有效的检查配对的方法
Is there a more efficient way of checking pairs?
我正在编写一个程序,该程序分发"手牌"并检查是否有一对或同花顺。我很好奇是否有一种比下面的代码更有效的方法来检查任何两个元素是否匹配。谢谢你!
//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(),一个接一个地执行,这取决于相同数量的卡牌的数量。只要确保它们不冲突
-
将所有元素放到一个容器中:
std::vector<Card> cards = /* ... */ ;
-
将元素按顺序排列。
sort(begin(cards), end(cards));
-
查看是否有重复的卡片:
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"四种"。
请注意,对于一张五张牌的手牌,我不知道它会比每一张牌与其他牌进行对比计算更有效率。
相关文章:
- C++:正在检查LinkedList中的回文-递归方法-错误
- 检查哪个对象调用了另一个对象的对象方法
- 检查两个节点在子节点上是否具有相同状态的更优雅的方法
- 检查类是否在方法中实例化
- 检查类方法中是否(此 == nullptr)
- 检查子类型时的专用方法模板
- 检查两个向量是否并行的最有效方法
- 如何检查在编译时是否调用了模板化方法?
- 尝试编译SFINAE检查中使用的方法体时发生编译错误
- 有没有一种简单的方法来检查C++中的不安全表达式
- 是否有更有效的方法来检查元素是否在给定的区间内
- 检查特定目录中是否存在与文件匹配的 abc* 的最佳方法
- 检查数组是否等于的最快方法?
- 替换枚举以最大化编译时间检查的最佳方法
- 双重检查创建单例问题的方法
- 如果方法不进行类型检查,为什么C++模板匹配?
- C++:检查向量中的元素是否大于另一个具有相同索引的元素的有效方法?
- 检查子类是否执行了方法重写
- 最快/最小方法检查字符串是否包含多个单词
- SFINAE c++方法检查