Inf1 OP : Lab Sheet Week 2 Q11 - Gambler's Ruin
Overview
Warning
Pair Programming:
This exercise is reserved for pair programming in the live lab sessions.
Please skip it when doing the exercises individually.

On p. 66 of the Sedgewick & Wayne textbook, the following block of code is given:

public class Gambler
{
  public static void main(String[] args)
  {
    int stake = Integer.parseInt(args[0]);
    int goal = Integer.parseInt(args[1]);
    int num_trials = Integer.parseInt(args[2]);

    int bets = 0;
    int wins = 0;

    for (int t = 0; t < num_trials; t++)
    {
      int cash = stake;
      while (cash > 0 && cash < goal)
      {
        bets++;
        if (Math.random() < 0.5 ) cash++;
        else                      cash--;
      }
      if (cash == goal) wins++;
    }

    System.out.println(100 * wins/num_trials + "% wins");
    System.out.println("Avg # bets: " + bets/num_trials);

  }
}

Note

In S&W, the authors use a variable T. For greater clarity, we have renamed it as num_trials.

Familiarise yourself with the Gambler’s Ruin code and run it with some different parameters.

Adjust the program so that the probability of a win, prob_of_win, can also be given as a command-line parameter. Your program should now be called as follows:

:java Gambler <stake:int> <goal:int> <num_trials:int> <prob_of_win:double>

where <variable-name:variable-type> tells you the types of expected command-line parameters. For example,

:java Gambler 2 20 5 0.75

should make the program run with the assignments stake = 2, goal = 20, num_trials = 5 and prob_of_win = 0.75.

An automated test has been created for this exercise: GamblerTest.java.