// Arup Guha
// 11/14/2016
// Simulation corresponding to question 10 from COT 3100 Fall 2016 Homework #6

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define NUMTRIALS 1000000

int trial();
int drawRand(int* arr, int len);

int main() {

    srand(time(0));

    // Try a million trials.
    int i, successes = 0;
    for (i=0; i<NUMTRIALS; i++)
        successes += trial();

    // Print out the experimental probability of success (1 ace in each of 4 hands.)
    printf("Prob success = %lf.\n", (double)successes/NUMTRIALS);

    return 0;

}

// Returns 1 for a successful trial, 0 otherwise.
int trial() {

    int deck[52];
    int i,j;
    for (i=0; i<52; i++) deck[i] = i;

    // Draw the whole deck at random.
    int res[52];
    for (i=0; i<52; i++)
        res[i] = drawRand(deck, 52-i);

    // Let each value of i represent one hand.
    for (i=0; i<4; i++) {

        // Ace count for hand i.
        int numA = 0;

        // Hand i's cards are 13*i through 13*i+12, see how many of these are aces.
        for (j=0; j<13; j++)

            // The aces are card #s 0, 13, 26 and 39...
            if (res[13*i+j]%13 == 0)
                numA++;

        // If any hand doesn't have precisely one case, the try is a failure.
        if (numA != 1) return 0;
    }

    // If we get here, we have a success.
    return 1;
}

// Draws a random card from arr[0..len-1], then adjusts arr to copy its last card into
// that random spot, in essence, removing that one random card from the deck.
int drawRand(int* arr, int len) {
    int index = rand()%len;
    int retval = arr[index];
    arr[index] = arr[len-1];
    return retval;
}
