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

#define STR_LENGTH 256
#define STEP       1000
#define XMAX       100.0
#define MMAX       10.0
#define QMAX       10.0


typedef struct _dot
  {double x;
   double y;
  } dot; 
 
typedef dot* pdot;

int main(void)
 {int    np,i,j,h,hits,besthits=-1;
  pdot   pda;
  double eps,r,m,q,x,bestm,bestq;
  char   s[STR_LENGTH];
  
  start:
   printf("Numero di punti: "); scanf("%s",s); np=atoi(s);  
   printf("Epslon: "); scanf("%s",s); eps=atof(s);
   printf("Rumore: "); scanf("%s",s); r=atof(s);
   printf("m: ");      scanf("%s",s); m=atof(s);
   printf("q: ");      scanf("%s",s); q=atof(s);  

   printf("Acquisiti np=%d eps=%.2f r=%.2f m=%.2f q=%.2f. Confermi (s,S,y,Y/altro==NO)?",np,eps,r,m,q); 
   scanf("%s",s);
   switch(s[0])
    { case 's': 
      case 'S':
      case 'y':
      case 'Y': break;
      default : goto start;
    }
  
   if ((pda=(pdot)malloc(sizeof(dot)*np))==NULL) goto mem_err;

   srand(time(NULL));
   for(i=0;i<np;i++)
    {pda[i].x=x=(XMAX*rand())/RAND_MAX;
     pda[i].y=m*x+q+((2.0*rand())/RAND_MAX-1.0)*r;
    }

   for(i=0,m=0.0;i<STEP;i++,m+=MMAX/(STEP-1))
    for(j=0,q=0.0;j<STEP;j++,q+=QMAX/(STEP-1))
     {for(h=hits=0;h<np;h++)
       if (fabs(pda[h].x*m+q-pda[h].y)<eps) hits++;
      if (hits>besthits) {besthits=hits; bestm=m; bestq=q;}
     }
     
   printf("Fit migliore m=%.5f q=%.5f hits=%d\n",bestm,bestq,besthits);

   return EXIT_SUCCESS;

  mem_err: printf("Memoria insufficiente\n"); return EXIT_FAILURE;
 }
