From page 28 on this pdf:
1. What is the “if (t == goal) wins++; ” keeping track of?
2. What does the outer loop control?
3. What happens at each trial?
4. What is the identifier “win” for?
5. What is the “stake” for?
6. What is the “goal” for?
7. How many trials would produce a good result?
8. How do you read the output in plain English?
% java Gambler 5 25 1000
203 wins of 1000
- If you were running this program to find the probability of winning in this game, what would need to be done to come up with the best approximation to the actual value?
a. Implement another loop that will increase the goal by doubling it at every iteration and report the conclusion. Keep all other variables fixed. The stake should be $5.
b. Implement another loop that will increase the trials by factors of 10 it at every iteration and report the conclusion. Keep all other variables fixed. The stake should be $5.
Challenge (Optional):
Add what is needed to be able to systematically increase both the goals and the trials. Report your result in full a sentence.
public class Gambler
{
public static void main(String[] args)
{
int stake = Integer.parseInt(args[0]);
int goal = Integer.parseInt(args[1]);
int trials = Integer.parseInt(args[2]);
int wins = 0;
for (int i = 0; i < trials; i++)
{
int t = stake;
while (t > 0 && t < goal)
{
if (Math.random() < 0.5) t++;
else t--;
}
if (t == goal) wins++;
}
StdOut.println(wins + " wins of " + trials);
}
}