Friday 28 June 2013

Monty Hall problem (Three-Door problem)

http://en.wikipedia.org/wiki/Monty_Hall_problem

image

The most well known statement of the problem is:

Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice? (Whitaker, 1990, as quoted by vos Savant 1990a)

Vos Savant's response was:

Yes; you should switch. The first door has a 1/3 chance of winning, but the second door has a 2/3 chance. Here’s a good way to visualize what happened. Suppose there are a million doors, and you pick door #1. Then the host, who knows what’s behind the doors and will always avoid the one with the prize, opens them all except door #777,777. You’d switch to that door pretty fast, wouldn’t you?

image

image

So the ratio between WIN vs LOSE should be 66.6 : 33.3

I spend some time to write a simulator to check. (code is a bit ugly but it works)

Game class:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package montyhallproblem;

/**
*
* @author celeron533
*/
public class Game {

public Door[] doors;

public Game() {
this.doors = new Door[]{new Door(), new Door(), new Door()};//create doors
doors[(int) (Math.random() * 3)].item = Item.car;//allocate the prize
}
public int playerInitial;

public void playerInitialSelection(int s) {
playerInitial = s;
}

public int hostOpenGoatDoor() {
if (doors[playerInitial].item == Item.car) {
//open one door of the rest
int open;
do {
open = (int) (Math.random() * 3);
} while (open == playerInitial);
doors[open].opened = true;
return open;
} else {//when player select a goat door, host open the left goat door
for (int i = 0; i < 3; i++) {
if (i == playerInitial) {//skip player selection
continue;
} else {
if (doors[i].item == Item.car) {//skip car door
continue;
} else {//open
doors[i].opened = true;
return i;
}
}
}
}
return -1;
}

public class Door {

public boolean opened = false;
public Item item = Item.goat;
}

public enum Item {
car, goat
}

@Override
public String toString() {
String result = "select_" + playerInitial + " ";
for (int i = 0; i < 3; i++) {
result += doors[i].item + "_" + doors[i].opened + " ";
}
return result;
}
}


Main class:


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package montyhallproblem;

/**
*
* @author celeron533
*/
public class MontyHallProblem {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Game game;
int playerSelect, hostOpen;
int keepSelectionWins = 0;
int switchSelectionWins = 0;
for (int i = 0; i < 10000000; i++) {
game = new Game();
playerSelect = (int) (Math.random() * 3);
game.playerInitialSelection(playerSelect);
hostOpen = game.hostOpenGoatDoor();
//Statistical results
if (game.doors[playerSelect].item == Game.Item.car) {
keepSelectionWins++;
} else {
switchSelectionWins++;
}
//System.out.println(game.toString());
}
System.out.println("keepSelectionWins: " + keepSelectionWins);
System.out.println("switchSelectionWins:" + switchSelectionWins);
}
}


 


And the perfect result:


run:
keepSelectionWins: 3333349
switchSelectionWins:6666651
BUILD SUCCESSFUL (total time: 3 seconds)


image

Monday 10 June 2013

Create a Simple Java REST Web Service Client

A web service is a method of communication between two electronic devices over the World Wide Web.  [Wikipedia]

Unlike some private protocol, RESTful web service use common web protocol and encapsulate data into XML format.

For example, client sent a photo search request to flickr:

http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=b673a1be26fa7463c7036d9d0e3339e7&text=gundam&format=rest&api_sig=028e6e4f5041b8974069d4ead1f7f2ea

And flickr will response

<?xml version="1.0" encoding="utf-8" ?>
<rsp stat="ok">
<photos page="1" pages="1842" perpage="100" total="184172">
<photo id="9004970606" owner="91423658@N05" secret="fb1d4dbf62" server="5340" farm="6" title="gundam" ispublic="1" isfriend="0" isfamily="0" />
<photo id="9004399158" owner="32670813@N07" secret="978879e163" server="7325" farm="8" title="Bandai advertisement in Gundam Seed Destiny Remaster" ispublic="1" isfriend="0" isfamily="0" />
</photos>
</rsp>

 


===============Create the project in Netbeans=================


Create a new Java Application


image


 


Right click on your project –> New –> Other…


In ‘Web Services’ category, select ‘RESTful Java Client’ file


image


Follow the wizard, java codes and xml schema will be generated automatically.


image


In NewJerseyClient.java, all APIs are listed. You only need to call the mapped function with proper parameters and the function will raise a connection and make a request.


The Rsp.java is used to unmarsal the XML response.


 


# Do NOT forget to add the app key in your request.


## Because this in only a very simple example, you need to disable the ‘login’ authority function.


 


Sample code:


public static void main(String[] args) {
// TODO code application logic here
NewJerseyClient flickrREST = new NewJerseyClient();
RestResponse result = flickrREST.photo_search("gundam");
unmarsal(result.getDataAsString());
}

private static void unmarsal(String xml) {
ByteArrayInputStream stream=new ByteArrayInputStream(xml.getBytes());
Rsp rsp = JAXB.unmarshal(stream, Rsp.class);
System.out.println("Stat:"+rsp.getStat());
Rsp.Photos photos = rsp.getPhotos();
System.out.println("Page:" + photos.getPage() + " Pages:" + photos.getPages()
+ " PerPage:" + photos.getPerpage() + " TotalResults:" + photos.getTotal());
for (Rsp.Photo photo : photos.getPhoto()) {
System.out.println("PhotoID:" + photo.getId() + " Title:" + photo.getTitle());
}
}



===========More works could be done to improve the user interface====


image