/////////////////////
// NormalRandom.java
// Gerry Broennimann, ib03, 11.4.05
//
// Zweck: Erzeugt normal-verteilte Zufallszahlen
//
// Idee: Kugel durch ein Nagelbrett fallen lassen
//
// Die Kugel faellt mit p=0.5 bei jedem Nagel nach links (bzw. rechts).
// Jede Nagelreihe enthaelt einen Nagel mehr als die obere Reihe.
// Die Hoehe des Nagelbrettes (height) entspricht der Anzahl "slots", in die
// eine Kugel fallen kann.
// Je hoeher das Nagelbrett, desto feiner ist die Unterteilung.
//
// Modell:
//
//       0
//      0 1
//     0 1 2
//    0 1 2 3
//   0 1 2 3 4
//  0 1 2 3 4 5  etc.
//
// Bemerkung:
// Innerhalb eines Slots sind die Zufallszahlen gleichverteilt!
//
//
// Erweiterungs-Ideen:
// - Zufallszahlen speichern (z.B. in einer Datei)
// - Graphische Ausgabe der Zahlen / Slots -> Applet/Application
//


public class NormalRandom
{
	static int height = 20;
	static int slots = height;
	static double slot[];
	static int numbers = 50000; // Anzahl Zufallsziehungen


	public static void main(String args[])
	{
		System.out.println("slots: "+slots);
		slot = new double[slots];
		for(int i=0; i<numbers; i++)
		{
			//System.out.println("# "+i);
			random();
		}
		printSlots();
	}


	public static double random()
	{
		// Grenzen / Intervall der Zufallsziehung
		double low = 0; // untere Grenze
		double top = 1; // obere Grenze
		double interval = 1.0 / height;

		int tempSlot = 0;
		int slotNr;

		// Kugel fallen lassen:

		for(int i=0; i<height-1; i++)
		{
			if (Math.random() <= .5) // "Kugel" nach links gefallen
			{
				tempSlot = tempSlot; // "Positions-Index" bleibt
			}
			else // "Kugel" nach rechts gefallen
			{
				tempSlot++;// "Positions-Index" erhoeht sich
			}
		}
		slotNr = tempSlot;
		slot[slotNr]++;	// misst die Anzahl "Kugeln" in einem Slot

		// aus der slotNr die Grenzen / Intervall bestimmen
		low = slotNr*(interval);
		top = (slotNr+1)*(interval);

		// Zufallszahl im bestimmten Intervall ziehen
		return (low+Math.random()*top);
	}

	public static void printSlots()
	{
		for(int i=0;i<slots; i++)
		{
			System.out.println("#"+i+"  "+(int)slot[i]);
		}
	}
}