📄 genericalgorithm.cpp
字号:
// GenericAlgorithm.cpp
#include "stdafx.h"
#include "GenericAlgorithm.h"
#include <time.h>
#include <stdlib.h>
#include <math.h>
namespace
{
bool InitializeRandGenerator()
{
srand((unsigned int)time(NULL));
return true;
}
bool _nomeaning = InitializeRandGenerator();
}
// for common function
double BinaryParse(const BinBits& bits)
{
int numer = 0;
int denumer = 1;
for (int i = SAMPLELENGTH - 1; i >= 0; --i)
{
if (bits[i] == '1')
{
numer += denumer;
}
denumer += denumer;
}
return static_cast<double>(numer) / static_cast<double>(denumer);
}
// for MySample
void MySample::Init()
{
// initialize binary string
for (size_t i = 0; i < SAMPLELENGTH; ++i)
{
if ((rand()%2) == 1)
{
_bits[i] = '1';
}
else
{
_bits[i] = '0';
}
}
// initialize action
_action = DONE;
}
double MySample::Fitness()
{
double x = LOWBOUNARY + ZOOMSCALE * BinaryParse(_bits);
_fitvalue = x * sin(10.0 * x) +1.0;
// _fitvalue = 1 - (x * x) ; // f(x) = 1 - x^2
return _fitvalue;
}
void MySample::CalcuPro(double sumfit)
{
_prop = _fitvalue / sumfit;
// decide what to do in next step
if ( static_cast<double>(rand()) / static_cast<double>(RAND_MAX) < _prop )
{
_action = STAY;
}
else
{
_action = CROSSOVER;
}
}
void MySample::CrossOver(MySample& rhs)
{
size_t pos = rand() % SAMPLELENGTH;
// cross over at pos
MyBit tmp;
for (size_t i = 0; i < pos; ++i)
{
tmp = _bits[i];
_bits[i] = rhs._bits[i];
rhs._bits[i] = tmp;
}
_action = STAY;
}
void MySample::Mutate()
{
size_t pos = rand() % SAMPLELENGTH;
if (_bits[pos] == '1')
{
_bits[pos] = '0';
}
else
{
_bits[pos] = '1';
}
_action = STAY;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -