// coinflips.java
// This applet simulates flipping 30 coins, and counts the number of HHHHH and TTTTT (5-in-a-row) sequences

// Written by Russ Woodroofe, 
//  modifying an applet of Julian Devlin, 8/97, for the text book
// "Introduction to Probability," by Charles M. Grinstead & J. Laurie Snell
// Available under the GNU General Public License, v2.0 or greater

// Packages we need
import java.awt.*;
import java.applet.Applet;
import java.util.Random;


public class coinflips extends Applet
{
	TextArea disp;		// Area to display random numbers
	
	Panel contp;		// Panel for user controls
	
	Label numl;			// Controls
	TextField num;
	Button go;
	
	Random randGen;		// Random number generator
	
	// Initialize applet
	public void init()
	{	
		numl = new Label("No.");			// Create controls
		num = new TextField("100", 4);
		go = new Button("Go");
		
		contp = new Panel();				// Set up control panel
		contp.add(numl);					
		contp.add(num);
		contp.add(go);
		contp.setLayout(new FlowLayout());
		
		disp = new TextArea(20, 30);		// Create display area
		
		resize(500,400);					// Set up applet
		setLayout(new FlowLayout());
		add(disp);
		add(contp);
		
		validate();
		
		randGen = new Random();			// Create random number generator
	}
	
	// Handle events
	public boolean handleEvent(Event evt)
	{
		if (evt.target instanceof Button)
		{
			if (evt.target == go && evt.id == Event.ACTION_EVENT)	
					// When button is clicked
			{
				disp.setText("");			// Reset output window
        		generate(Integer.valueOf(num.getText()).intValue());
        		return true;		// Generate correct number of random floats				
											
			}
		}
		return super.handleEvent(evt);	// Handle other events as usual
	}
	
	public void generate(int n)
	{
		float randFloat;
		char tosses[] = new char[30];
		int successes;
		int success_array[] = new int[6];
		float percent;

		for(int i = 0; i < n; i++)
		{
			// Toss 30 coins
			for (int j = 0; j < 30; j++)
			{
				randFloat = randGen.nextFloat();
				if (randFloat < .5)
					tosses[j]='H';
				else
					tosses[j]='T';
			}

			// Count the number of 5-in-a-row sequences.  Such sequences start at or before coin 25
			successes=0;
			for (int j = 0; j<26; j++)
			{
				if (tosses[j]==tosses[j+1] && tosses[j]==tosses[j+2] && tosses[j]==tosses[j+3] && tosses[j]==tosses[j+4])
					successes++;
			}
			if (successes < 6)
				success_array[successes]++;

		}

		// Print results
		for (successes=0; successes<6; successes++)
		{
			percent = ( (float) success_array[successes]/ (float) n) * 100;
			disp.appendText("\n% with ");
			disp.appendText(Integer.toString(successes));
			disp.appendText(" sequences of 5-in-a-row: ");
			disp.appendText(Float.toString(percent));
		}
	}
	
}
