From 40ee7ad5aeadeb9823e1cd6e1218a1999c608a65 Mon Sep 17 00:00:00 2001 From: Mike Buland Date: Mon, 9 Jul 2012 08:39:37 -0600 Subject: New libgenetic. Genetic algorithms, only good. --- src/operatorbasic.cpp | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/operatorbasic.cpp (limited to 'src/operatorbasic.cpp') diff --git a/src/operatorbasic.cpp b/src/operatorbasic.cpp new file mode 100644 index 0000000..ce37f78 --- /dev/null +++ b/src/operatorbasic.cpp @@ -0,0 +1,48 @@ +#include "genetic/operatorbasic.h" +#include "genetic/phenotype.h" + +#include +#include +using namespace Bu; + +Genetic::OperatorBasic::OperatorBasic( Phenotype *pProgenitor, + float fMutationRate ) : + pProgenitor( pProgenitor ), + fMutationRate( fMutationRate ) +{ +} + +Genetic::OperatorBasic::~OperatorBasic() +{ + delete pProgenitor; +} + +Genetic::Phenotype *Genetic::OperatorBasic::random() +{ + Genetic::Phenotype *pNew = pProgenitor->makeEmptyOffspring(); + pNew->randomize(); + return pNew; +} + +Genetic::Phenotype *Genetic::OperatorBasic::mate( + const Genetic::PhenotypeList &lParents ) +{ + Genetic::Phenotype *pChild = lParents.first()->makeEmptyOffspring(); + + // Right now, we assume both parents have the same amount of "DNA" + int iSplitPoint = ((uint32_t)Bu::Random::rand())%lParents.first()->getSize(); + pChild->copyFrom( *lParents.first(), 0, iSplitPoint ); + pChild->copyFrom( *lParents.last(), iSplitPoint, + lParents.last()->getSize()-iSplitPoint ); + + // Mutate the child some + for( int j = 0; j < pChild->getSize(); j++ ) + { + //sio << Bu::Random::randNorm() << sio.nl; + if( Bu::Random::randNorm() <= fMutationRate ) + pChild->mutate( j, 1.0 ); + } + + return pChild; +} + -- cgit v1.2.3