import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Illustrates a statistical concept known as the gambler's ruin. A gambler repeatedly 
 * tosses a coin, winning a dollar for heads and losing a dollar for tails. This game 
 * continues until the gambler runs out of money. It can be shown mathematically that the 
 * balance will eventually reach 0 regardless of its initial value. 
 * 
 * This program prompts the user for an initial balance and simulates the gambler's ruin.
 * It outputs the maximum balance achieved during the game and the total number of coin
 * flips.
 *
 * @author Drue Coles
 */
public class GamblersRuin {

    public static void main(String[] args) {
        System.out.print("Enter initial balance: $");
        Scanner in = new Scanner(System.in);
        final int initBalance = in.nextInt();

        int balance = initBalance;
        int maxBalance = initBalance;
        int coinFlips = 0;

        // Simulate the game. 
        ThreadLocalRandom coin = ThreadLocalRandom.current();
        while (balance > 0) {
            coinFlips++;
            if (coin.nextBoolean()) {
                balance++;
            } else {
                balance--;
            }

            if (balance > maxBalance) {
                maxBalance = balance;
            }
        }

        System.out.printf("Initial balance: $%,d%n", initBalance);
        System.out.printf("Maximum balance: $%,d%n", maxBalance);
        System.out.printf("Length of game: %,d coin flips%n", coinFlips);
    }
}