/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-  */
/*
 * main.c
 * Copyright (C) 2016 drdev <drdev@localhost.com>
 * 
 * coin_flip is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * coin_flip is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
 /*
 Person A flips a coin until he sees a head followed by a tail.
 Person B flips a coin until he sees two heads in a row.
 In the long run, A will need four flips to get his result,
 while B will require six flips.
 */

#include <stdio.h>
#include <time.h>
#include <math.h>

#define trials 100000
#define sequence 1 //1 for sequence A, 0 for sequence B


/* Prototypes */
char *strcpy(char *dest, const char *src);
void exit(int status);
void srand(unsigned int seed);
int rand();
int flip_coin();
/* end of prototypes */

char fn1[64];
FILE *outdata;
unsigned long i, sum;
int flips,last_flip,current_flip;

int flip_coin()
{
//returns a 1 (head) or 0 (tail)
return(rand() % 2);
}


int main(int argc, char *argv[])
{
if (argc<2)
{
strcpy(fn1,"output.txt");
}
else
{
strcpy(fn1,argv[1]);
}

printf("\nOutput file selected = %s\n",fn1);

if ((outdata = fopen(fn1,"w"))==NULL)
	{printf ("\nOutput file cannot be opened.\n");
	exit (1);}

srand(time(NULL));
sum=0;

for(i=1;i<=trials;i++)
{
last_flip=flip_coin();
current_flip=flip_coin();
flips=2;
if(sequence)
{
while(!((last_flip==1)&&(current_flip==0)))
{
last_flip=current_flip;
current_flip=flip_coin();
flips++;
}
sum=sum+flips;
fprintf(outdata,"%d\n",flips);
}
else
{
while(!((last_flip==1)&&(current_flip==1)))
{
last_flip=current_flip;
current_flip=flip_coin();
flips++;
}
sum=sum+flips;
fprintf(outdata,"%d\n",flips);
}

}

printf("%f\n",(float)sum/trials);
	
printf("Done\n");

fclose(outdata);

return (0);
}
