/*
  This is a test program for PGAPack.  The objective is to maximize the
  number of 1-bits in a chromosome.
*/

#include "pgapack.h"

double evaluate ( PGAContext *ctx, int p, int pop );
int myMutation(PGAContext *, int, int, double);

/*******************************************************************
*                   user main program                              *
*******************************************************************/
int main( int argc, char **argv )
{
     PGAContext *ctx; 

     ctx = PGACreate ( &argc, argv, PGA_DATATYPE_BINARY, 100, PGA_MAXIMIZE );
     PGASetRandomSeed(ctx, 1);
     PGASetMaxIter(ctx, 50);
     PGASetUserFunction(ctx, PGA_USERFUNCTION_MUTATION, (void *)myMutation);
     PGASetUp                (ctx);
     PGARun                  (ctx, evaluate);
     PGADestroy              (ctx);
     return(0);
}


/*******************************************************************
*               user defined evaluation function                   *
*   ctx - contex variable                                          *
*   p   - chromosome index in population                           *
*   pop - which population to refer to                             *
*******************************************************************/
double evaluate ( PGAContext *ctx, int p, int pop )
{
     int i, nbits;
     int stringlen;

     stringlen = PGAGetStringLen(ctx);
     
     nbits = 0;
     for ( i=0; i<stringlen; i++ )
	  if ( PGAGetBinaryAllele(ctx, p, pop, i) )
	       nbits++;
     
     return((double) nbits);
}

int myMutation(PGAContext *ctx, int p, int pop, double mr)
{
     int i, found = 0, stringlen;

     stringlen = PGAGetStringLen(ctx);
     for (i = 0; i < stringlen && !found; i++)
	  if (!PGAGetBinaryAllele(ctx, p, pop, i))
	  {
	       PGASetBinaryAllele(ctx, p, pop, i, 1);
	       found = 1;
	  }
     return (found);
}

