⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 objfunc.cpp

📁 这是遗传算法的源代码
💻 CPP
字号:
// -*- c++ -*-
//
//  File:         objfunc.cpp
//
//  Description:  This function evaluates m blokcs of k=4 variables and returns the sum.
//		  Suppose each group has x_1, x_2, x_3 and x_4 variables with cardinality 
//		  c_1, c_2, c_3 and c_4. The sub-function would be x_1+x_2+x_3+x_4 except
//		  for the case of sum = 0. The it would return c_1 + c_2 + c_3 + c_4 + 1.
//
//                Change this for different problems.
//
//  Author:       Fernando Lobo
//
//  Date:         June/1999
//
//  Extended to deal with chi-ary problems by Luis de la Ossa
//  GCC 3.4 and 4 series compliance by Kumara Sastry 
//
//  Date:         March/2006

#include "objfunc.hpp"
#include "chromosome.hpp"
#include "parameter.hpp"
#include "utility.hpp"

#include <stdio.h>

// These variables are specific for this objective function.

int m;
int k;
int* maxSums;

// Converts the chromosome to an array of integer and call objective_func.
double objfunc( chromosome &x )
{
   //
   // convert chromosome to an array of integer
   //
   int *iar = new int [ x.length() ];
   x.asIntegerArray( iar );       
   //
   // call objective function
   //    
   double v = objective_func( iar, x.length() );
   delete [] iar;
   return v;
}

//------------------------------------------------------------


// Return the sum of each block.
int sum ( int *chrom, int start, int end )
{
  int sum = 0;
  for( int i=start; i<= end; i++ )
    sum+=chrom[i];
  return sum;
}

// Sets up the objective function. For this, calculates and stores
// the maximum value of each one of the m blocks.
void set_objective_function()
{
  k = 4;
  m = parameter::lchrom/k;
  maxSums = new int[m];
  
  for( int i=0; i<m; i++ ) {
    int start = i*k;
    int end = start + k - 1;
    maxSums[i] = sum ( parameter::ranges, start, end );  
  }
}

// Objective function
// In this case, the chromosome is decoded into bits whose position is choosen randomly
// when the problem is set. Then trap 4 function is evaluated.
double objective_func( int *chrom, int lchrom )
{
  int k=4;  
  double m = parameter::lchrom/k;
    
  // sum a bunch of functions
  double accum = 0.0;
  for( int i=0; i< m; i++ ) {
    int start = i*k;
    int end = start + k - 1;
    int pSum = sum ( chrom, start, end );      
    if (pSum==0) 
      accum += (maxSums[i] + 1);
    else
      accum += pSum;
  }
  return accum;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -