// Monte-Carlo simulations // #include #include #include void shuffle( int a[], int n) { // put array into random order while( n > 1) { int i = rand() % n; // random position 0 ... n-1 --n; int t = a[i]; a[i] = a[n]; a[n] = t; // swap a[i] and a[n] } } int trial( void) // return 1 for success, otherwise 0 { // int c = rand() % 2; // coin flip: 1 for heads, 0 for tails // return c; // // int d1 = rand() % 6 + 1, d2 = rand() % 6 + 1; // two 6-sided dice // if( d1 + d2 == 7) return 1; // // blackjack: int a[52]; for( int i = 0; i < 52; ++i) a[i] = i % 13 + 1; // 1 to 13, 4 times shuffle( a, 52); int c1 = a[0], c2 = a[1]; // first two cards, check Ace+Ten or Ten+Ace if( (c1 == 1 && c2 >= 10) || (c2 == 1 && c1 >= 10) ) return 1; return 0; } int main( void) { srand(time(0)); int n = 10000, count = 0; // number of trials, number of successes for( int i = 0; i < n; ++i) count += trial(); double p = count/(double)n; // probability of success printf( "count = %i, trials = %i, p = %g\n", count, n, p); return 0; }