Gambler.java
This is the syntax highlighted version of Gambler.java
from 2.3 Conditionals, Loops of
Introduction to Computer Science by
Robert Sedgewick and Kevin Wayne.
/*************************************************************************
* Compilation: javac Gambler.java
* Execution: java Gambler stake goal N
*
* Simulates a gambler who start with $stake and place fair $1 bets
* until she goes broke or reach $goal. Keeps track of the number of
* times she wins and the number of bets she makes. Run the experiment N
* times, averages the results, and prints them out.
*
* % java Gambler 50 250 1000
* Percent of games won = 19.0
* Avg # bets = 9676.302
*
* % java Gambler 50 150 1000
* Percent of games won = 31.9
* Avg # bets = 4912.13
*
* % java Gambler 50 100 1000
* Percent of games won = 49.6
* Avg # bets = 2652.352
*
*************************************************************************/
public class Gambler {
public static void main(String[] args) {
int stake = Integer.parseInt(args[0]);
int goal = Integer.parseInt(args[1]);
int N = Integer.parseInt(args[2]);
int bets = 0; // total number of bets made
int wins = 0; // total number of games won
// play the game N times
for (int i = 0; i < N; i++) {
int t;
for (t = stake; t > 0 && t < goal; bets++) {
if (Math.random() < 0.5) t++;
else t--;
}
if (t == goal) wins++;
}
// print results
System.out.println("Percent of games won = " + 100.0 * wins / N);
System.out.println("Avg # bets = " + 1.0 * bets / N);
}
}
Last updated: Thu Sep 16 11:36:57 EDT 2004
.
Copyright © 2004, Robert Sedgewick and Kevin Wayne.