Listing 3: The KSGenome class

//
//  ksgenome.h - knapsack genome
//  derived from bit string genome.
//  It represents a  solution 
//  to 0-1 knapsack problem.
////////////////////////////////////////

#ifndef KSGENOME_H
#define KSGENOME_H
#include "gagenome.h"

////////////////////////////////////////
class KSGenome:public GABitStringGenome
{
public :
   //
   // List of profits and weights for each item.
   static   int      m_maxItems ;
   static   double*  m_profit   ;
   static   double*  m_weight   ;
   static   double   m_maxCapacity;
   static   double   m_penalty  ;

   //--------------------------------
   void   Initialize()
   {
      // size of bit string is m_maxItems.
      SetSize(m_maxItems);
      Randomize();
   }

   //--------------------------------
   double   KSGenome::Evaluate()
   {
      double totalProfit = 0;
      double totalWgt = 0;
      //
      // Evaluate function adds up the 
      // profit for all the included items
      for (int i=0;i<m_maxItems;i++)
      {
         if (IsSet(i))
         {
            totalProfit += m_profit[i];
            totalWgt += m_weight[i];
         }
      }
      //
      // if the weight exceeds the capacity
      // subtract the penalty function
      double exceed = totalWgt - m_maxCapacity;
      if (totalWgt > m_maxCapacity)
      {
         totalProfit -= m_penalty*exceed;
      }
      return totalProfit;
   }
};

#endif
— End of Listing —