# include # include # include using namespace std; int main ( ) // // DUEL_MANY carries out the duel many times, and prints the estimated // probabilities of survival. // { int i, n, one_wins, seed, two_wins, winner; int duel_once ( ); cout << "Enter number of times the duel will be fought.\n"; cin >> n; seed = time ( 0 ); srand48 ( seed ); one_wins = 0; two_wins = 0; for ( i = 1; i <= n; i++ ) { winner = duel_once ( ); if ( winner == 1 ) { one_wins = one_wins + 1; } else { two_wins = two_wins + 1; } } cout << "\n"; cout << "The duel was fought " << n << " times.\n"; cout << "Player 1 has a winning probability of " << ( double ) one_wins / double ( n ) << "\n"; cout << "Player 2 has a winning probability of " << ( double ) two_wins / double ( n ) << "\n"; return 0; } int duel_once ( ) // // 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. // { int shot, winner; // // Initialize the random number generator. // 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 winner; }