1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
#include <string>
#include <algorithm>
struct Card
{
std::string face;
std::string suit;
};
constexpr std::size_t NCARDS = 5 ;
using hand = Card[NCARDS] ;
bool is_straight( const hand& h )
{
static const std::string face[] { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
// get the face values as integers 1(Ace), 2, ... 13(King)
int values[NCARDS] ;
for( std::size_t i = 0 ; i < NCARDS ; ++i )
values[i] = std::find( std::begin(face), std::end(face), h[i].face ) - std::begin(face) + 1 ;
// sort face values in ascending order
std::sort( values, values+NCARDS ) ;
// check if the sorted sequence is a straight
// http://en.cppreference.com/w/cpp/algorithm/search
// http://en.cppreference.com/w/cpp/algorithm/equal
static const int straight[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
static const int straight2[] { 1, 10, 11, 12, 13 }; // straight: Ace, Ten, Jack, Queen, King
return ( std::search( std::begin(straight), std::end(straight), values, values+NCARDS ) != std::end(straight) )
|| std::equal( std::begin(straight2), std::end(straight2), values, values+NCARDS ) ;
}
int main()
{
const hand a { { "Five", "Clubs" }, { "Four", "Spades" }, { "Six", "Diamonds" }, { "Three", "Clubs" }, { "Seven", "Hearts" } };
std::cout << std::boolalpha << is_straight(a) << '\n' ; // true
const hand b { { "Queen", "Clubs" }, { "Ten", "Spades" }, { "Jack", "Diamonds" }, { "Ace", "Clubs" }, { "King", "Hearts" } };
std::cout << std::boolalpha << is_straight(b) << '\n' ; // true
const hand c { { "Queen", "Clubs" }, { "Two", "Spades" }, { "Jack", "Diamonds" }, { "Ace", "Clubs" }, { "King", "Hearts" } };
std::cout << std::boolalpha << is_straight(c) << '\n' ; // false
}
|