#include <iostream>
#include <iomanip>
#include <math.h>
#include <fstream>
using namespace std;

int main()
{
	char puffer[255] = "";
	int anzahl=0;
	int position=0;
	float summen[10], quadratsummen[10];
	float zufallszahl=0;
	float x_erw=0, x2_erw=0, x_stabw=0;
	float p=0;
	ofstream ausgabe;
	
	
	cout << "Aufgabe 20: Random Walk\n";
	
	// Anzahl der Versuche ermitteln
	do
	{
		cout << "Wieviele Versuche N>0 sollen durchgefuehrt werden? [10]: ";
		cin.getline(puffer,sizeof(puffer),'\n');
		if((string)puffer == "")
		{
			anzahl = 10;
		}
		else
		{
			anzahl = atoi(puffer);
		}
	}while(!(anzahl > 0));
	
	// Wahrscheinlichkeit p ermitteln
	do
	{
		cout << "Bitte geben Sie nun den Wahrscheinlichkeitswert 0 < p < 1 an? [0.7]: ";
		cin.getline(puffer,sizeof(puffer),'\n');
		if((string)puffer == "")
		{
			p = 0.7;
		}
		else
		{
			p = atof(puffer);
		}
	}while(!((p > 0) && (p < 1)) );
	
	// Zufallsgenerator initialisieren
	srand((unsigned int)time(0));
	
	
	// N experimente durchfuehren
	for(int i=1;i <= anzahl;i++)
	{
		// Jeweils 1000 mal den random walk ausfuehren
		position = 0;
		for(int j=1; j <= 1000;j++)
		{
			zufallszahl = rand()/(double)RAND_MAX;
			if(zufallszahl < p)
			{
				position++;
			}
			else
			{
				position--;	
			}
			if(j%100 == 0)
			{
				summen[j/100] += position;
				quadratsummen[j/100] += pow(position,2);  
			}
		}
	}
	
	// So, nun an die auswertung:
	
	cout << "Ergebnisse:\n" << setw(12) << "Zeitpunkt t" << setw(10) <<  "<x>" << setw(10) << "dx" << endl;
	
	// Zunaechst Ausgabedatei oeffnen:
	
	ausgabe.open("a20-res.dat");
	if(!ausgabe)
	{
		cerr << "Fehler beim oeffnen der Ausgabedatei\n";
		return(1);
	}
	for(int i=1;i<=10;i++)
	{
		cout << setw(12) << i;
		ausgabe << i << " ";
		x_erw = summen[i] / anzahl;
		x2_erw = quadratsummen[i] / anzahl;
		x_stabw = sqrt(x2_erw - pow(x_erw,2));
		cout << setw(10) <<  x_erw << setw(10) << x_stabw << endl;
		ausgabe << x_erw << " " << x_stabw << endl;
	}
	ausgabe.close();
	cout << "Soll das Ergebnis im Gnuplot angezeigt werden? (j/n) [j]: ";
	cin.getline(puffer,sizeof(puffer),'\n');
	if((string)puffer != "n")
	{
		system("gnuplot -persist a20-gnuplot.gp");
		system("gnuplot -persist a20.2-gnuplot.gp");
	}
	return(0);
}
