基于遗传算法的寻路模拟

这篇博客介绍了作者利用遗传算法实现寻路演示程序的学习过程。虽然遗传算法效率较低,但作为学习示例,其直观性有助于理解。文章包含了遗传算法类、地图类的代码文件,以及寻路前后的结果展示,显示出遗传算法在寻路问题上的局限性,但在特定问题解决上有其价值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习了些人工智能的东西, 利用遗传算法来写了一个寻路的演示程序, 虽然该算法效率底下, 但作为一个学习程序还是有直观性;

先把代码和结果贴上, 有时间再写分析

遗传算法类

主要有两个类: 基因编码类和基因组类;

"GeGroup.h"

#ifndef  _GEGROUP_HBB_
#define  _GEGROUP_HBB_
#include "HMap.h"
#include "Global.h"
#include <bitset>
class HMap;
class GeCode
{
public:
	GeCode();
	~GeCode();
	std::bitset<LEN_BIT_ROUTE> mGeRoute;
	int mHighestFitSce;
	int mHighestSceStep;
	void Clear();
	// decode generic
	SearchDir DeCode(const int StepIndex);
};

class  GeGroup
{
public:
	GeGroup(HMap& m);
	~GeGroup();
	GeCode mGrop[NUM_GEGROUP];
	GeCode mFitGes[NUM_GEGROUP];
	int mBestGeIndex;
	int mTotalFitSce;
	HMap& mMap;
	bool Epoch();
	bool UpdateFitnessScore();
	GeCode WheelSelect();
private:
	int mGenerationCount;
	static const int mMaxScore = NUM_MAX_GRID*NUM_MAX_GRID*4;
	inline bool  IsCrossOver(){return RandInt(0,10) <= RATE_CROSSOVER;}
	inline bool IsMutation(){return RandInt(0,1000) <= RATE_MUTATION;}
	int CalcuFitScore(const int idx);
	int CalcuPosScore(const point& p);
	void CrossOver(const int mom, const int dad);
	void Mutate(const int geLst);
	bool EvolutionSelection();
	void ShowMarkMap();
};

#endif //  _GEGROUP_HBB_

"GeGroup.cpp"

#include "GeGroup.h"
#include <cassert>
#include <iostream>
#include "HMap.h"
#include <stdlib.h>
using namespace std;

static const int MAX_INT = 0x7fffffff;

GeCode::GeCode():mHighestFitSce(0),mHighestSceStep(0)
{

}
GeCode::~GeCode(){}

SearchDir  GeCode::DeCode(const int StepIndex)
{
	int codePos = StepIndex*LEN_BIT_CODE;
	unsigned Dir = 0;
	Dir |= (1u&mGeRoute[codePos]) | ((1u&mGeRoute[codePos+1])<<1) | ((1u&mGeRoute[codePos+2])<<2);
	return (SearchDir)Dir;
}

void GeCode::Clear()
{
	for(int i = 0; i < LEN_BIT_ROUTE; ++i)
		mGeRoute[i] = 0;
	mHighestSceStep = 0;
	mHighestFitSce = 0;
}

/*******************************
///           class GeGroup
*******************************/
GeGroup:: GeGroup(HMap& m):mBestGeIndex(0),mTotalFitSce(0)
	,mMap(m),mGenerationCount(0)
{
	for(int i = 0; i < NUM_GEGROUP;++i)
	{
		for(int j = 0; j<LEN_BIT_ROUTE;++j)
			mGrop[i].mGeRoute[j] = RandInt(0,1);
	}
}

GeGroup::~ GeGroup()
{
	//dtor
}

int GeGroup::CalcuPosScore(const point& p)
{
	// the longer distance, th
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值