


//  KNAPSACK  fitness function.  

//  Jeff Horn, 11/00, to be used in the GA++ code for CS 422.

#include <iostream.h>
#include <stdio.h>
#include <fstream.h>

void main()
{
  const int CHROMLENGTH = 20;
  const int MAX_WEIGHT = 233;
  bool chromosome[CHROMLENGTH];
  int weights[CHROMLENGTH] = {435,77,66,33,44,55,22,11,99,88,49,13,24,98,506,12,76,44,102,11};
  int chromposition;
  int weight;
  char tempchar;


  FILE *inputfile, *outputfile;

  inputfile = fopen("chromosome","r");           // try to open the input file
  if(!inputfile) {perror("Error opening chromosome input file"); /* exit(1); */}

  tempchar = getc(inputfile);                    //  get first bit
  for (chromposition = 0; chromposition < CHROMLENGTH; chromposition++)
      {                                          // get rest of bits
       if(tempchar == '0')
          chromosome[chromposition] = 0;
          else chromosome[chromposition] = 1;
       tempchar = getc(inputfile);
      }
  if (inputfile != NULL)                      //   close input file 
    fclose(inputfile); 

  weight = 0;
  for (chromposition = 0; chromposition < CHROMLENGTH; chromposition++)
      {
       if(  chromosome[chromposition]) 
          weight += weights[chromposition];
      }
  if(weight > MAX_WEIGHT) weight = -1;

  outputfile = fopen("fitness","w");            //  try to open output file
  if(!outputfile) {perror("Error opening fitness output file"); /* exit(1); */}
  fprintf(outputfile,"%d\n",weight);     //   print number of ones to file
  if (outputfile != NULL)                      //   close output file 
    fclose(outputfile); 
} 
       
  int BinaryCodedInteger(int begin, int end, bool chromosome[])
    {
     int bci=0;
     for(int i=begin;i<end;i++)
        {
         bci = 2 * bci;
         if(chromosome[i])
           bci++;
        }
     return(bci);
     }

