## Tuesday, April 7, 2009

### Using Java to build a Probabilistic Model

Imagine a box containing 64 beads, of which 32 are red and 32 are blue. Imagine selecting beans one at a time, noting their colour and returning them to the box. We can synthesise this with a few lines of Java as follows:

`public class prob1 {public static void main(String[] args) {int num1 = 0;String beancolor = new String("blue");System.out.println("Generated from box 32");int count = 1;    while (count < 11) {          num1 = (int)(Math.random() * 64);System.out.println("random no: " + num1);if (num1>32) {beancolor = "red";}else {beancolor = "blue";}System.out.println("bean colour: " + beancolor);          count++;    }}}`
And the output might look something like:

Generated from box 32
random no: 42
bean colour: red
random no: 12
bean colour: blue
random no: 5
bean colour: blue
random no: 48
bean colour: red
random no: 14
bean colour: blue
random no: 60
bean colour: red
random no: 35
bean colour: red
random no: 53
bean colour: red
random no: 9
bean colour: blue
random no: 59
bean colour: red

That was easy. Now imagine 64 boxes containing from 1 to 64 red beads and from 63 to zero blue beads, and 64 children each taking it in turn to remove one bead, note the colour, and return it. And imagine for each red bean a score of 1 is recorded, and for each blue bean a score of zero is recorded. This might be synthesised in Java as follows:

`public class prob2 {public static void main(String[] args) {int num1 = 0;int boxnum = 1;int result = 0;String boxno = new String("Item ");while (boxnum < 65) {boxno = boxno + boxnum + ", ";int count = 1;     while (count < 65) {           num1 = (int)(Math.random() * 64);if (num1 > boxnum) { result = 0;}else { result = 1;}boxno = boxno + result + ", ";           count++;     }System.out.println(boxno);boxno = "Box ";boxnum++;}}}`
That certainly fills the command window, but I must learn how to write it all to a file so I can pull it into a spreadsheet. The instructions are in the Java tutorial on this page and the code might look like this:
`import java.io.IOException;import java.io.FileWriter;import java.io.PrintWriter;public class prob3 {public static void main(String[] args) throws IOException {PrintWriter outputStream = null;try{int num1 = 0;int boxnum = 1;int result = 0;String boxno = new String("Item ");outputStream = new PrintWriter(new FileWriter("results.csv"));while (boxnum < 65) {boxno = boxno + boxnum + ", ";int count = 1;     while (count < 65) {           num1 = (int)(Math.random() * 64);if (num1 > boxnum) { result = 0;}else { result = 1;}boxno = boxno + result + ", ";           count++;     }outputStream.println(boxno);boxno = "Item ";boxnum++;}} finally {outputStream.close();}}}`

This generates a .csv file, which can be pulled straight into a spreadsheet, and I'll look more closely at that in my next blog.