C++ C++;在字符串向量中查找字符串的频率
我目前正在开发一个小型程序,它将确定一个由5个字符串组成的向量是否包含一个完整的房子。在我的程序中,一个满屋子的人有一对卡片和3张同类卡片 例如:C++ C++;在字符串向量中查找字符串的频率,c++,string,vector,poker,C++,String,Vector,Poker,我目前正在开发一个小型程序,它将确定一个由5个字符串组成的向量是否包含一个完整的房子。在我的程序中,一个满屋子的人有一对卡片和3张同类卡片 例如:[“A”、“A”、“A”、“K”、“K”]将是一个满屋子,而[“10”、“J”、“10”、“10”、“10”]将不是一个满屋子 我已经编写了我的主函数,用户可以使用下面的代码将卡值读入向量: int main() { vector<string> hand; string input; for (int i = 0
[“A”、“A”、“A”、“K”、“K”]
将是一个满屋子,而[“10”、“J”、“10”、“10”、“10”]
将不是一个满屋子
我已经编写了我的主函数,用户可以使用下面的代码将卡值读入向量:
int main()
{
vector<string> hand;
string input;
for (int i = 0; i < 5; i++)
{
cout << "Card " << i + 1 << ": ";
cin >> input;
hand.push_back(input);
}
}
intmain()
{
矢量手;
字符串输入;
对于(int i=0;i<5;i++)
{
cout您可以使用标准算法编写如下函数:
bool isFullHouse(vector<string> hand)
{
// put all cards matching the first one at the beginning
auto p = std::partition(hand.begin(), hand.end(),
[first_card = hand[0]] (auto card) {
return first_card == card;
});
// count cards matching the first one
auto num = std::distance(hand.begin(), p);
return (p == 2 or p == 3) // 2 or 3 cards
&& std::equal(hand.begin() + 1, p, hand.begin()) // same card at the beginning
&& std::equal(p + 1, hand.end(), p); // same card at the end
}
bool-isFullHouse(矢量手)
{
//将与第一张卡匹配的所有卡放在开头
auto p=std::partition(hand.begin(),hand.end(),
[第一张卡=手[0]](自动卡){
返回第一张卡片==卡片;
});
//清点与第一张相匹配的卡片
auto num=std::distance(hand.begin(),p);
返回(p==2或p==3)//2或3张卡
&&std::equal(hand.begin()+1,p,hand.begin())//开头是同一张卡
&&std::equal(p+1,hand.end(),p);//末尾是同一张卡
}
这里的效率不是一个主要问题,因为您处理的是一个由5个短字符串组成的向量,但这是一个O(n)
算法。因为您只有5张卡,所以n
并不相关,但这里使用的所有算法都是O(n)
注意:卡片编码中的一个常见惯例是使用T
表示10,这样所有卡片都是一个字符,当与套装配对时就像2S
或TC
,非常可预测且易于使用。提示:对数组进行排序。如果前两个和后三个匹配,或前三个和后两个匹配,则会检测到满屋。I“d如上所述进行排序,但您也可以使用map
对卡片进行计数,然后检查组合是否正确。我支持使用std::map
的想法,其中std::string
是卡片值(作为字符串)或“手”int
是出现的次数。在这个主题上,对于数量有限的手,可以对手本身进行散列,以快速确定是否有满屋。std::无序地图满屋;
排序。
bool isFullHouse(vector<string> hand)
{
// put all cards matching the first one at the beginning
auto p = std::partition(hand.begin(), hand.end(),
[first_card = hand[0]] (auto card) {
return first_card == card;
});
// count cards matching the first one
auto num = std::distance(hand.begin(), p);
return (p == 2 or p == 3) // 2 or 3 cards
&& std::equal(hand.begin() + 1, p, hand.begin()) // same card at the beginning
&& std::equal(p + 1, hand.end(), p); // same card at the end
}