# include # include # include using namespace std; int main ( ) // // DUEL_ONCE simulates a duel between players of equal accuracy. // The players alternate until one has been hit. // For this situation, with accuracies of 1/2, the first player has a 2/3 // chance of surviving, simply by going first. // // I had to use SRAND48() and DRAND48(), because generating a few real random // numbers with SRAND() seeded by TIME() and r = rand()/RAND_MAX ends up // producing essentially the same random real numbers each time! After a few // calls, things improve, but for this example that's too late. // { int seed, shot, winner; // // Initialize the random number generator. // seed = time ( 0 ); srand48 ( seed ); winner = 0; shot = 0; while ( winner == 0 ) { shot = shot + 1; if ( drand48 ( ) <= 0.5 ) { winner = 1; break; } shot = shot + 1; if ( drand48 ( ) <= 0.5 ) { winner = 2; break; } } cout << "Duel was won by " << winner << " after " << shot << " shots.\n"; return 0; }