// LondonBombs.java // Written by Julian Devlin, 8/97, for the text book // "Introduction to Probability," by Charles M. Grinstead & J. Laurie Snell import java.applet.Applet; import java.awt.*; public class LondonBombs extends java.applet.Applet { Float[] bombX; Float[] bombY; Float[] xc; // Variables for simulation - on unit circle Float[] yoc; Float[] yec; Float[] abgX; Float[] abgY; int[][] hits; OESpikeGraph oesg; // AWT elements BombArea ba; Label message; Button go; TextField num; Panel graphArea; Panel controls; JRandom myRand; // Set up all controls and put them in the window public void init() { message = new Label("No. of Bombs ="); // Create controls go = new Button("Simulate"); num = new TextField(4); graphArea = new Panel(); // Set up window controls = new Panel(); setLayout(new BorderLayout(5, 5)); controls.setLayout(new FlowLayout()); controls.add(message); controls.add(num); controls.add(go); oesg = new OESpikeGraph(); // initialize a graphing space ba = new BombArea(); add("Center", graphArea); graphArea.setLayout(new GridLayout(2, 1)); graphArea.add(ba); graphArea.add(oesg); add("South", controls); myRand = new JRandom(); } // Does the simulation, creating two arrays to store game states, then passes them // to a AreaBarGraph public void simulate(int n) { bombX = new Float[n + 1]; // Make arrays bombY = new Float[n + 1]; xc = new Float[11]; yoc = new Float[11]; yec = new Float[11]; hits = new int[10][10]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { hits[i][j] = 0; } } int[] temp = new int[11]; for (int i = 0; i < 11; i++) { xc[i] = new Float(i); yec[i] = new Float((float) Math.pow(Math.E, (double) -1 * (double) n / (double) 100) * (float) Math.pow((double) n / (double) 100, (double) i) / Combinatorics.fact(i)); temp[i] = 0; } for (int i = 0; i < n + 1; i++) { // Do actual simulation bombX[i] = new Float(myRand.nextFloat(0, 1)); bombY[i] = new Float(myRand.nextFloat(0, 1)); hits[(int) Math.floor(bombX[i].floatValue() * 10)] [(int) Math.floor(bombY[i].floatValue() * 10)]++; } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (hits[i][j] < 11) temp[hits[i][j]]++; } } for (int i = 0; i < 11; i++) { yoc[i] = new Float((float) temp[i] / (float) 100); } graphArea.remove(ba); graphArea.remove(oesg); ba = new BombArea(bombX, bombY); oesg = new OESpikeGraph(xc, yoc, yec); // Create new AreaBarGraph graphArea.add(ba); graphArea.add(oesg); validate(); } // Watch for a click on the go button public boolean action(Event evt, Object arg) { if (evt.target instanceof Button) { if ((String)arg == "Simulate") { int n = 0; try { n = Integer.parseInt(num.getText().trim()); // Get user input } catch (Exception e) { num.setText(""); validate(); } simulate(n); } } return true; } public Insets insets() { return new Insets(5,5,5,5); } }