flush_prob.cppΒΆ

// flush_prob.cpp

// A more efficient way to estimate the probability of a 5-card flush (as
// compared to the top_5_same_suit_experiment in cards.cpp). Some results:
//
// num_trials = 100000000 (1 billion)
//
//        cards.cpp: ~257s  (no optimization)
//   flush_prob.cpp: ~22s   (no optimization)
//
//        cards.cpp: ~134s  (-O3 optimization)
//   flush_prob.cpp: ~11s   (-O3 optimization)
//

#include <iostream>
#include <vector>

using namespace std;

void test1() {
    srand(time(NULL));

    // Since we only care about the suits of the cards, we will only store
    // the suits as the numbers 0, 1, 2, and 3.

    // Initialize the cards to {0, 1, 2, 3, 0, 1, 2, 3,  ..., 3}.
    vector<int> card(52);
    for(int i = 0; i < 52; ++i) {
        card[i] = i % 4;
    }

    const int num_trials = 100000000;
    int count = 0;
    for(int trial = 0; trial < num_trials; ++trial) {
        // Choose 5 cards at random from the deck, swapping them to the front.
        // This way we don't need to shuffle all 52 cards, which saves time.
        swap(card[0], card[0 + rand() % 52]);
        swap(card[1], card[1 + rand() % 51]);
        swap(card[2], card[2 + rand() % 50]);
        swap(card[3], card[3 + rand() % 49]);
        swap(card[4], card[4 + rand() % 48]);

        // Check if the first 5 suits are all the same.
        int suit = card[0];
        if (suit == card[1] && suit == card[2] && suit == card[3] && suit == card[4]) {
            count++;
        }
    }
    cout << count << " flushes in " << num_trials << " deals\n";
    cout << (100 * double(count) / num_trials) << "% chance of a 5-card flush\n";
}

int main() {
    test1();
}