Example: Poker Probability
Wish to compute the probability in 5 card stud of making a straight flush
Will create abstract data types to have card
Will use vector and shuffle from STL
#include <iostream> #include <vector> #include <algorithm> #include <assert.h> #include <ctime> using namespace std; enum class suit:short {SPADE, HEART, DIAMOND, CLUB}; class pips{ public: pips(int val):v(val){assert(v>0 && v<14);} friend ostream& operator<<(ostream& out, const pips& p); int get_pips(){return v;} private: int v; }; class card{ public: card():s(suit::SPADE), v(1){} card(suit s, pips v):s(s), v(v){} friend ostream& operator << (ostream& out, const card& c); suit get_suit(){return s;} pips get_pips(){return v;} private: suit s; pips v; }; ostream& operator<<(ostream& out, const pips& p){ out << p.v; return out; suit s = suit :: SPADE; } ostream& operator<<(ostream& out, const card& c){ out << c.v <<int(c.s) << endl; return out; } void init_deck(vector <card> &d){ for(int i=1; i<14; ++i){ card c1(suit::SPADE, i); card c2(suit::HEART, i); card c3(suit::DIAMOND, i); card c4(suit::CLUB, i); d[i-1] = c1; d[i+12] = c2; d[i+25] = c3; d[i+38] = c4; } } void print(vector<card> &deck){ for(auto cardval:deck) cout << cardval; cout << endl; } bool is_flush(vector<card> &hand){ suit s = hand[0].get_suit(); for(auto p=hand.begin()+1; p!=hand.end(); ++p){ if(s != p->get_suit()) return false; } return true; } bool is_straight(vector<card> &hand){ int pips_v[5], i=0; for(auto p=hand.begin(); p!=hand.end(); ++p) pips_v[i++] = (p -> get_pips()).get_pips(); sort(pips_v, pips_v+5); if(pips_v[0] != 1) return(pips_v[0] == pips_v[1]-1&&pips_v[1]==pips_v[2]-1&&pips_v[2]==pips_v[3]-1&&pips_v[3]==pips_v[4]-1); else return((pips_v[1]==2&&pips_v[2]==3&&pips_v[3]==4&&pips_v[4]==5)|| (pips_v[1]==10&&pips_v[2]==11&&pips_v[3]==12&&pips_v[4]==13)); } bool is_straight_flush(vector<card> &hand){ return is_flush(hand)&&is_straight(hand); } int main(){ //card c(suit::HEART, 5) ; //cout << c; vector<card> deck(52); init_deck(deck); //print(deck); srand(time(0)); int how_many=0; int flush_count=0; int str_count=0; int str_flush_count=0; cout << "How Many shuffles?" << endl; cin >> how_many; for(int loop=0; loop<how_many; ++loop){ random_shuffle(deck.begin(), deck.end()); vector<card> hand(5); int i = 0; for(auto p=deck.begin(); i<5; ++p) hand[i++] = *p; if(is_flush(hand)) flush_count++; if(is_straight(hand)) str_count++; if(is_straight_flush(hand)) str_flush_count++; } cout << "Flushes " << flush_count << " out of " << how_many << endl; cout << "Straights " << str_count << " out of" << how_many << endl; cout << "Straight Flushes " << str_flush_count << " out of " << how_many <<endl; }