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

📄 chromosome.cpp

📁 这是遗传算法的源代码
💻 CPP
字号:
// -*- c++ -*- ////  File:         chromosome.cpp////  Description:  C++ implementation for the class chromosome.//                A chromosome is an array of genes.      ////  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 <iostream>#include <iomanip>#include <assert.h>#include "random.hpp"#include "chromosome.hpp"#include "gene.hpp"#include "parameter.hpp"#include "objfunc.hpp"extern randomG RANDOM;// initializes a chromosome. alleles are not initialized.chromosome::chromosome( int ell ){  Length = ell;  genes = new gene[ Length ]; // allocate memory  Fitness = 0;}// copy constructorchromosome::chromosome(const chromosome &chrom){  genes = new gene[ chrom.Length ];  // allocate memory  for( int i=0; i< chrom.Length; i++ )     // copy the genes    genes[i] = chrom.genes[i];      Length = chrom.Length;    Fitness = chrom.Fitness;}// destructorchromosome::~chromosome(){  delete [] genes;  // free memory}// set the genes of the chromosome with random allelesvoid chromosome::random(){  for( int i=0; i< Length; i++ )    genes[i].random(i);}// assignment operatorchromosome & chromosome::operator=(const chromosome &chrom){  if (this == &chrom)    return *this;  for( int i=0; i< chrom.Length; i++ )     // copy the genes    genes[i] = chrom.genes[i];    Length = chrom.Length;  Fitness = chrom.Fitness;  return *this;}// randomly mutates the genes of this chromosome.void chromosome::mutate(double pmut){  for( int i=0; i< Length; i++)    if (RANDOM.flip(pmut))                        // toss a biased coined      genes[i].mutate(i);}//// Convert a chromosome to an array of integer.// Storage for the array must be allocated beforehand.//void chromosome::asIntegerArray( int *iar ){  int size = Length;  for( int i=0; i< size; i++ )      iar[i] = genes[i].allele();}//// copy 'n' genes specified by 'locus' of chromosome 'C' into this chromosome//void chromosome::copyGenes( chromosome &C, int *locus, int n ){  for( int i=0; i< n; i++ )    genes[ locus[i] ] = C.genes[ locus[i] ];}// print the chromosomestd::ostream &operator<< (std::ostream &out, chromosome &chrom){  if( parameter::report_string )    for( int i=0; i< chrom.Length; i++)      out << chrom.genes[i];  if( parameter::report_fitness )   out << "   f= " << chrom.Fitness;    return out;}// evaluate fitness functionvoid chromosome::evaluate() { Fitness = objfunc(*this); };

⌨️ 快捷键说明

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