Towers Of Hanoi

Java Code

/**
 * MontyHallProblem.java
 * Created by Stijn Strickx on Nov. 2 2005
 * Copyright 2005 Stijn Strickx, All rights reserved
 */

import java.io.*;
import java.util.Random;
public class MontyHallProblem {
public static void main(String[] arguments) throws java.io.IOException {

	long TotalTries = 0;
	long TotalSuccess = 0;
	float PercentageSuccess = 0;
	long TotalTriesMax = 0;
	int position = 0;
	int choice = 0;
	int CancelledDoor = 1;
	int SecondChoice = 1;

	TotalTriesMax = getNumber("How many times will you try to win the car? ");

		for(TotalTries = 0; TotalTries <= TotalTriesMax; TotalTries = TotalTries + 1){

			Random r = new Random();
			position = r.nextInt();
			position = Math.abs(position);
			position = position%3;
			position = position+1;
			
			Random p = new Random();
			choice = p.nextInt();
			choice = Math.abs(choice);
			choice = choice%3;
			choice = choice+1;

				if(choice != position){
				TotalSuccess = TotalSuccess + 1;
				CancelledDoor = 6 - choice - position;
				if(TotalTriesMax < 101)
				System.out.print("You chose door " + choice);
				System.out.print(" and the car was behind door " + position); 
				System.out.print(", the quizmaster cancelled door " + CancelledDoor);
				System.out.print(", you changed your choice and won the car behind door "); 
				System.out.println(position + ".");
				}

				if(choice == position){
				CancelledDoor = 6 - position - choice - 1;
				CancelledDoor = Math.abs(CancelledDoor);	
				SecondChoice = 6 - CancelledDoor - position;
				if(TotalTriesMax < 101)
				System.out.print("You chose door " + choice); 
				System.out.print(", the car was behind this door, the quizmaster cancelled door "); 
				System.out.print(CancelledDoor + ", you changed your choice to door ");
				System.out.println(SecondChoice + " and didn't win the car.");
				}

				if(TotalTries == TotalTriesMax){
				PercentageSuccess = (TotalSuccess / (float)TotalTriesMax) * 100;
				System.out.print("Because you always changed doors, you have a success rate of: "); 
				System.out.print(PercentageSuccess + "%");
				}
		}
	}
	static long getNumber(String question) throws java.io.IOException {
		String theNumber;
		long number = 0;
		BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
		System.out.print(question);
		theNumber = in.readLine();
		System.out.println();
		number = Long.parseLong(theNumber);
		return number;
	}
}

Home | Code | Learn
© 2007-2008 ProgLogic, all rights reserved. | ProgLogic.com is created by Stijn Strickx. | e-mail