// CLTGeneral.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 CLTGeneral
	extends java.applet.Applet
{
	Float[] xSpikes;		// Variables for simulation
	Float[] ySpikes;
	Float[] xLines;
	Float[] yLines;
	
	LineSpikeGraph lsg;				// AWT elements
	
	Panel dispArea;
	Panel controls;		// Panel for user controls
	
	Label numl1, numl2;			// Controls
	TextField num1, num2;
	Button go;
	
	GridBagLayout gbl;
	GridBagConstraints cc;
	
	float mean, std;
	int highest;
	JRandom myRand;
		
	// Initialize applet
	public void init()
	{	
		numl1 = new Label("Maximum range =");			// Create controls
		num1 = new TextField("5", 4);
		numl2 = new Label("No. of summands =");			// Create controls
		num2 = new TextField("3", 4);
		go = new Button("Go");
		
		lsg = new LineSpikeGraph(); // initialize a graphing space
		
		dispArea = new Panel();				// Set up window
		controls = new Panel();
		setLayout(new BorderLayout(5, 5));
		
		add("South", controls);
		add("Center", dispArea);
		
		dispArea.setLayout(new GridLayout(1, 1));
		dispArea.add(lsg);
		
		gbl = new GridBagLayout();
		controls.setLayout(gbl);
		
		cc = new GridBagConstraints();
		
		cc.gridx = 0;
		cc.gridy = 0;
		gbl.setConstraints(numl1, cc);
		controls.add(numl1);
		
		cc.gridx = 1;
		gbl.setConstraints(num1, cc);
		controls.add(num1);
		
		cc.gridx = 0;
		cc.gridy = 1;
		gbl.setConstraints(numl2, cc);
		controls.add(numl2);
		
		cc.gridx = 1;
		gbl.setConstraints(num2, cc);
		controls.add(num2);
		
		cc.gridx = 0;
		cc.gridy = 2;
		cc.gridwidth = 2;
		gbl.setConstraints(go, cc);
		controls.add(go);
		
		myRand = new JRandom();
		highest = 0;
		validate();
	}
	
	// Handle events
	public boolean handleEvent(Event evt)
	{
		String minStr, maxStr;
		if (evt.target instanceof Button)
		{
			if (evt.target == go && evt.id == Event.ACTION_EVENT)	// When button is clicked
			{
				simulate(Integer.valueOf(num1.getText()).intValue(),
        				Integer.valueOf(num2.getText()).intValue());
        		return true;					// Generate correct number of tosses
			}
		}
		return super.handleEvent(evt);	// Handle other events as usual
	}
	
	public float normal(float x, float mu, float sigma) {
		return 1 / (sigma * (float)  Math.pow(2 * Math.PI, .5)) * 
			(float) Math.pow(Math.E, -1 * Math.pow(x - mu, 2) / (2 * 
				Math.pow((double) sigma, 2)));	
	}
	
	public float normalArea(float a, float b) {
		float mu = 0f;
		float sigma = 1f;
		int subdivisions = (int) Math.max(100, 20 * (double) Math.round(
			(double) b - (double) a + .5));
		float dx = (b - a) / (float) subdivisions;
		float sum = normal(a, mu, sigma) + normal(b, mu, sigma);
		float x;
		for (int k = 1; k < subdivisions; k++) {
			x = a + (float) k * dx;
			if (k % 2 == 1)
				sum += 4 * normal(x, mu, sigma);
			else
				sum += 2 * normal(x, mu, sigma);
		}
		return dx / 3 * sum;
	}
	
	public float[] convolve(float[] d1, float[] d2) {
		float[] results = new float[d1.length + d2.length - 1];
		for (int i = 0; i < results.length; i++) {
			results[i] = 0;	
		}
		for (int i = 0; i < d1.length; i++) {
			for (int j = 0; j < d2.length; j++) {
				results[i + j] += d1[i] * d2[j];	
			}	
		}	
		return results;
	}
	
	public int[] pickDistinct(int n, int total) {
		int[] results = new int[n];
		int[] range = new int[total];
		int index;
		for (int i = 0; i < total; i++) {
			range[i] = i;
		}
		for (int i = 0; i < n; i++) {
			index = myRand.nextInt(i, total - 1);
			results[i] = range[index];
			range[index] = range[i];
		}
		return results;
	}
	
	public float[] randomDensity(int n) {
		float[] results = new float[n];
		float sum = 0;
		for (int i = 0; i < n; i++) {
			results[i] = myRand.nextFloat();
			sum += results[i];
		}
		for (int i = 0; i < n; i++) {
			results[i] /= sum;
		}
		return results;
	}
	
	public float[] makeDensity(int r) {
		int m = myRand.nextInt(1, r);
		int[] ri = pickDistinct(m, r);
		float[] temp;
		temp = randomDensity(m);
		float[] p = new float[r];
		for (int i = 0; i < r; i++) {
			p[i] = 0;	
		}
		for (int i = 0; i < m; i++) {
			p[ri[i]] = temp[i];	
		}
		return p;
	}
	
	public void setPoints(int r, int num) 
	{
		float temp;
		float[] p;
		float[] q;
		q = makeDensity(r);
		p = q;
		for (int k = 2; k <= num; k++) {
			q = makeDensity(r);
			p = convolve(q, p);	
		}
	
		mean = 0;
		float variance = 0;
		for (int k = 0; k < p.length; k++) {
			mean += k * p[k];
			variance += (int) Math.pow((double) k, 2) * p[k];
		}
		variance -= (float) Math.pow((double) mean, 2);
		std = (float) Math.pow((double) variance, .5);
		if (std == 0)
			std = 1 / (r * (num - 1));		//??????????????
	
    	float xmin = -4f;
    	float xmax = 4f;
    	float dx = (xmax - xmin) / 100f;
    	
    	// +-1
    	int kmin = (int) Math.floor(Math.max(0, (double) (mean - 4 
    		* std))) + 1;
    	int kmax = (int) Math.ceil(Math.min((double) r * (num - 1),	///// 
    		(double) (mean + 4 * std))) - 1;
    	xLines = new Float[101];
    	yLines = new Float[101];
    	xSpikes = new Float[kmax - kmin + 1];
    	ySpikes = new Float[kmax - kmin + 1];
    		
    	for (int k = kmin; k <= kmax; k++) {
    		xSpikes[k - kmin] = new Float((k - mean) / std);
    		temp = (float) p[k] * std;
    		ySpikes[k - kmin] = new Float(temp);
	    }
	    
	    for (int i = 0; i < 101; i++) {
	    	xLines[i] = new Float(xmin + i * dx);
	    	yLines[i] = new Float(normal(xmin + i * dx, 0f, 1f));
	    }
	}
	
	// Calculate probabilities
    public void simulate(int r, int num)
    {	
    	setPoints(r, num);
	    
		dispArea.remove(lsg);
		lsg = new LineSpikeGraph(xLines, yLines, xSpikes, ySpikes);	// Create new LineSpikeGraph
		dispArea.add(lsg);							// Put up the graph
		validate();
	}
}




