summaryrefslogtreecommitdiff
path: root/src/operatorbasic.cpp
blob: ce37f78aa1379978adea8f3a131b895ac2aa4b43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "genetic/operatorbasic.h"
#include "genetic/phenotype.h"

#include <bu/random.h>
#include <bu/sio.h>
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;
}