/* parrondo-rand.c (Paradoxe de Parrondo)
 *
 * choix aléatoire des jeux A et B
 *
 * J-P. Davalan le 28/06/2003 licence GPL
 * 
 * compilation:
 * ------------
 * gcc -o parrondo-rand parrondo-rand.c
 *
 * utilisation:
 * ------------
 * parrondo-rand 0.005 0.35 0.5 0.0001 10000000 > alea2.g
 *
 * image postscript:
 * -----------------
 * echo 'set output "alea2.eps";set terminal postscript eps;set nokey;set grid;set xlabel "probab. de A" "times"; set ylabel "gain moyen";  plot [x=0.35:0.5] "alea2.g";'|gnuplot
 *
 * image png: (pstoimg fait partie de la distribution de latex2html)
 * ----------
 * pstoimg -antialias -aaliastext -o alea2.png alea2.eps
 */

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

double p1=0.5,p2=0.75,p3=0.1;
	
inline int jeu(double p, int n) {
  int i, t = 0, g;
  double a, u;
  for(i=0;i<=n;i++) {
    g=-1;
    a = (1.0*rand())/(RAND_MAX+1.0);
    u = (1.0*rand())/(RAND_MAX+1.0);
    if(a < p) {  // jeu A
      if(u < p1) g = 1;
    } else {     // jeu B
      if(t%3 != 0) {
	if(u < p2) g=1;
      } else if(u < p3) g=1;
    }
    t = t + g;
  }
  return t;
}
      
int main (int argc, char *argv[]) {
  double e, p, pmin, pmax, pstep;
  int s, n, m, i;
  if(argc<6) {
    printf("usage: %s e pmin pmax pstep nsimulations\n",argv[0]);
    exit(0);
  }
  e = strtod(argv[1],NULL);
  pmin = strtod(argv[2],NULL);
  pmax = strtod(argv[3],NULL);
  pstep= strtod(argv[4],NULL);
  n = (int)strtol(argv[5],NULL,10);
  if(e<0 || pmax<=pmin || pstep<=0 || n<1) {
    printf("e>=0, pmin < pmax, pstep >0, nsimulations > 0\n");
    exit(0);
  }
  p1 -=e; p2 -=e; p3 -=e;
  m=(int)(1+(pmax-pmin)/pstep);
    
  srand(time((time_t *)NULL));
  for(i=0;i<=m;i++) {
    p = pmin+i*pstep;
    s = jeu(p, n);
    printf("%f %f\n",p, (double)s/(n+1.0));
    fflush(stdout);
  }
  return 0;
}
  
