蚁群算法MATLAB代码

合集下载

蚁群算法

蚁群算法

蚁群算法报告及代码一、狼群算法狼群算法是基于狼群群体智能,模拟狼群捕食行为及其猎物分配方式,抽象出游走、召唤、围攻3种智能行为以及“胜者为王”的头狼产生规则和“强者生存”的狼群更新机制,提出一种新的群体智能算法。

算法采用基于人工狼主体的自下而上的设计方法和基于职责分工的协作式搜索路径结构。

如图1所示,通过狼群个体对猎物气味、环境信息的探知、人工狼相互间信息的共享和交互以及人工狼基于自身职责的个体行为决策最终实现了狼群捕猎的全过程。

二、布谷鸟算法布谷鸟算法布谷鸟搜索算法,也叫杜鹃搜索,是一种新兴启发算法CS算法,通过模拟某些种属布谷鸟的寄生育雏来有效地求解最优化问题的算法.同时,CS也采用相关的Levy飞行搜索机制蚁群算法介绍及其源代码。

具有的优点:全局搜索能力强、选用参数少、搜索路径优、多目标问题求解能力强,以及很好的通用性、鲁棒性。

应用领域:项目调度、工程优化问题、求解置换流水车间调度和计算智能三、差分算法差分算法主要用于求解连续变量的全局优化问题,其主要工作步骤与其他进化算法基本一致,主要包括变异、交叉、选择三种操作。

算法的基本思想是从某一随机产生的初始群体开始,利用从种群中随机选取的两个个体的差向量作为第三个个体的随机变化源,将差向量加权后按照一定的规则与第三个个体求和而产生变异个体,该操作称为变异。

然后,变异个体与某个预先决定的目标个体进行参数混合,生成试验个体,这一过程称之为交叉。

如果试验个体的适应度值优于目标个体的适应度值,则在下一代中试验个体取代目标个体,否则目标个体仍保存下来,该操作称为选择。

在每一代的进化过程中,每一个体矢量作为目标个体一次,算法通过不断地迭代计算,保留优良个体,淘汰劣质个体,引导搜索过程向全局最优解逼近。

四、免疫算法免疫算法是一种具有生成+检测的迭代过程的搜索算法。

从理论上分析,迭代过程中,在保留上一代最佳个体的前提下,遗传算法是全局收敛的。

五、人工蜂群算法人工蜂群算法是模仿蜜蜂行为提出的一种优化方法,是集群智能思想的一个具体应用,它的主要特点是不需要了解问题的特殊信息,只需要对问题进行优劣的比较,通过各人工蜂个体的局部寻优行为,最终在群体中使全局最优值突现出来,有着较快的收敛速度。

30个智能算法matlab代码

30个智能算法matlab代码

30个智能算法matlab代码以下是30个使用MATLAB编写的智能算法的示例代码: 1. 线性回归算法:matlab.x = [1, 2, 3, 4, 5];y = [2, 4, 6, 8, 10];coefficients = polyfit(x, y, 1);predicted_y = polyval(coefficients, x);2. 逻辑回归算法:matlab.x = [1, 2, 3, 4, 5];y = [0, 0, 1, 1, 1];model = fitglm(x, y, 'Distribution', 'binomial'); predicted_y = predict(model, x);3. 支持向量机算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3];y = [1, 1, -1, -1, -1];model = fitcsvm(x', y');predicted_y = predict(model, x');4. 决策树算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = fitctree(x', y');predicted_y = predict(model, x');5. 随机森林算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = TreeBagger(50, x', y');predicted_y = predict(model, x');6. K均值聚类算法:matlab.x = [1, 2, 3, 10, 11, 12]; y = [1, 2, 3, 10, 11, 12]; data = [x', y'];idx = kmeans(data, 2);7. DBSCAN聚类算法:matlab.x = [1, 2, 3, 10, 11, 12]; y = [1, 2, 3, 10, 11, 12]; data = [x', y'];epsilon = 2;minPts = 2;[idx, corePoints] = dbscan(data, epsilon, minPts);8. 神经网络算法:matlab.x = [1, 2, 3, 4, 5];y = [0, 0, 1, 1, 1];net = feedforwardnet(10);net = train(net, x', y');predicted_y = net(x');9. 遗传算法:matlab.fitnessFunction = @(x) x^2 4x + 4;nvars = 1;lb = 0;ub = 5;options = gaoptimset('PlotFcns', @gaplotbestf);[x, fval] = ga(fitnessFunction, nvars, [], [], [], [], lb, ub, [], options);10. 粒子群优化算法:matlab.fitnessFunction = @(x) x^2 4x + 4;nvars = 1;lb = 0;ub = 5;options = optimoptions('particleswarm', 'PlotFcn',@pswplotbestf);[x, fval] = particleswarm(fitnessFunction, nvars, lb, ub, options);11. 蚁群算法:matlab.distanceMatrix = [0, 2, 3; 2, 0, 4; 3, 4, 0];pheromoneMatrix = ones(3, 3);alpha = 1;beta = 1;iterations = 10;bestPath = antColonyOptimization(distanceMatrix, pheromoneMatrix, alpha, beta, iterations);12. 粒子群-蚁群混合算法:matlab.distanceMatrix = [0, 2, 3; 2, 0, 4; 3, 4, 0];pheromoneMatrix = ones(3, 3);alpha = 1;beta = 1;iterations = 10;bestPath = particleAntHybrid(distanceMatrix, pheromoneMatrix, alpha, beta, iterations);13. 遗传算法-粒子群混合算法:matlab.fitnessFunction = @(x) x^2 4x + 4;nvars = 1;lb = 0;ub = 5;gaOptions = gaoptimset('PlotFcns', @gaplotbestf);psOptions = optimoptions('particleswarm', 'PlotFcn',@pswplotbestf);[x, fval] = gaParticleHybrid(fitnessFunction, nvars, lb, ub, gaOptions, psOptions);14. K近邻算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = fitcknn(x', y');predicted_y = predict(model, x');15. 朴素贝叶斯算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = fitcnb(x', y');predicted_y = predict(model, x');16. AdaBoost算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3];y = [0, 0, 1, 1, 1];model = fitensemble(x', y', 'AdaBoostM1', 100, 'Tree'); predicted_y = predict(model, x');17. 高斯混合模型算法:matlab.x = [1, 2, 3, 4, 5]';y = [0, 0, 1, 1, 1]';data = [x, y];model = fitgmdist(data, 2);idx = cluster(model, data);18. 主成分分析算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; coefficients = pca(x');transformed_x = x' coefficients;19. 独立成分分析算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; coefficients = fastica(x');transformed_x = x' coefficients;20. 模糊C均值聚类算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; options = [2, 100, 1e-5, 0];[centers, U] = fcm(x', 2, options);21. 遗传规划算法:matlab.fitnessFunction = @(x) x^2 4x + 4; nvars = 1;lb = 0;ub = 5;options = optimoptions('ga', 'PlotFcn', @gaplotbestf);[x, fval] = ga(fitnessFunction, nvars, [], [], [], [], lb, ub, [], options);22. 线性规划算法:matlab.f = [-5; -4];A = [1, 2; 3, 1];b = [8; 6];lb = [0; 0];ub = [];[x, fval] = linprog(f, A, b, [], [], lb, ub);23. 整数规划算法:matlab.f = [-5; -4];A = [1, 2; 3, 1];b = [8; 6];intcon = [1, 2];[x, fval] = intlinprog(f, intcon, A, b);24. 图像分割算法:matlab.image = imread('image.jpg');grayImage = rgb2gray(image);binaryImage = imbinarize(grayImage);segmented = medfilt2(binaryImage);25. 文本分类算法:matlab.documents = ["This is a document.", "Another document.", "Yet another document."];labels = categorical(["Class 1", "Class 2", "Class 1"]);model = trainTextClassifier(documents, labels);newDocuments = ["A new document.", "Another new document."];predictedLabels = classifyText(model, newDocuments);26. 图像识别算法:matlab.image = imread('image.jpg');features = extractFeatures(image);model = trainImageClassifier(features, labels);newImage = imread('new_image.jpg');newFeatures = extractFeatures(newImage);predictedLabel = classifyImage(model, newFeatures);27. 时间序列预测算法:matlab.data = [1, 2, 3, 4, 5];model = arima(2, 1, 1);model = estimate(model, data);forecastedData = forecast(model, 5);28. 关联规则挖掘算法:matlab.data = readtable('data.csv');rules = associationRules(data, 'Support', 0.1);29. 增强学习算法:matlab.environment = rlPredefinedEnv('Pendulum');agent = rlDDPGAgent(environment);train(agent);30. 马尔可夫决策过程算法:matlab.states = [1, 2, 3];actions = [1, 2];transitionMatrix = [0.8, 0.1, 0.1; 0.2, 0.6, 0.2; 0.3, 0.3, 0.4];rewardMatrix = [1, 0, -1; -1, 1, 0; 0, -1, 1];policy = mdpPolicyIteration(transitionMatrix, rewardMatrix);以上是30个使用MATLAB编写的智能算法的示例代码,每个算法都可以根据具体的问题和数据进行相应的调整和优化。

蚁群算法路径优化matlab代码

蚁群算法路径优化matlab代码

蚁群算法路径优化matlab代码标题:蚁群算法路径优化 MATLAB 代码正文:蚁群算法是一种基于模拟蚂蚁搜索食物路径的优化算法,常用于求解复杂问题。

在路径优化问题中,蚂蚁需要从起点移动到终点,通过探索周围区域来寻找最短路径。

MATLAB 是一个常用的数值计算软件,可以用来实现蚁群算法的路径优化。

下面是一个基本的 MATLAB 代码示例,用于实现蚁群算法的路径优化:```matlab% 定义参数num_ants = 100; % 蚂蚁数量num_steps = 100; % 路径优化步数search_radius = 2; % 搜索半径max_iterations = 1000; % 最大迭代次数% 随机生成起点和终点的位置坐标start_pos = [randi(100), randi(100)];end_pos = [75, 75];% 初始化蚂蚁群体的位置和方向ants_pos = zeros(num_ants, 2);ants_dir = zeros(num_ants, 2);for i = 1:num_antsants_pos(i, :) = start_pos + randn(2) * search_radius; ants_dir(i, :) = randomvec(2);end% 初始化蚂蚁群体的速度ants_vel = zeros(num_ants, 2);for i = 1:num_antsants_vel(i, :) = -0.1 * ants_pos(i, :) + 0.5 *ants_dir(i, :);end% 初始时蚂蚁群体向终点移动for i = 1:num_antsans_pos = end_pos;ans_vel = ants_vel;for j = 1:num_steps% 更新位置和速度ans_pos(i) = ans_pos(i) + ans_vel(i);ants_vel(i, :) = ones(1, num_steps) * (-0.1 * ans_pos(i) + 0.5 * ans_dir(i, :));end% 更新方向ants_dir(i, :) = ans_dir(i, :) - ans_vel(i) * 3;end% 迭代优化路径max_iter = 0;for i = 1:max_iterations% 计算当前路径的最短距离dist = zeros(num_ants, 1);for j = 1:num_antsdist(j) = norm(ants_pos(j) - end_pos);end% 更新蚂蚁群体的位置和方向for j = 1:num_antsants_pos(j, :) = ants_pos(j, :) - 0.05 * dist(j) * ants_dir(j, :);ants_dir(j, :) = -ants_dir(j, :);end% 更新蚂蚁群体的速度for j = 1:num_antsants_vel(j, :) = ants_vel(j, :) - 0.001 * dist(j) * ants_dir(j, :);end% 检查是否达到最大迭代次数if i > max_iterationsbreak;endend% 输出最优路径[ans_pos, ans_vel] = ants_pos;path_dist = norm(ans_pos - end_pos);disp(["最优路径长度为:" num2str(path_dist)]);```拓展:上述代码仅仅是一个简单的示例,实际上要实现蚁群算法的路径优化,需要更加复杂的代码实现。

蚁群算法的Python代码及其效果演示(含注释)

蚁群算法的Python代码及其效果演示(含注释)

蚁群算法的Python代码及其效果演示(含注释)以下为基本蚁群算法的Python代码(含注释)。

随时可以运行:from turtle import*from random import*from json import loadk=load(open("stats.json"))city_num,ant_num=30,30 #规定城市和蚂蚁总数x_data=k[0] #城市的x坐标之集合y_data=k[1] #城市的y坐标之集合best_length=float("inf")best_path=[]alpha=1beta=7rho=0.5potency_list=[1 for xx in range(city_num**2)]Q=1##城市的index从0开始#下面列表存储城市间距离def get_i_index(n):if n%city_num==0:return n//city_num-1else:return n//city_numdef get_j_index(n):if n%city_num==0:return city_num-1else:return n%city_num-1distance_list=[((x_data[get_i_index(z)]-x_data[get_j_index(z)])**2+(y_data[get_i_index(z)]-y_data[get_j_index(z)])**2)**0.5 for z in range(1,city_num**2+1)]class ant(object):def __init__(self,ant_index):self.ant_index=ant_indexself.cities=list(range(city_num))self.current_length=0self.current_city=randint(0,city_num-1)self.initial_city=self.current_cityself.cities.remove(self.current_city)self.path=[self.current_city]self.length=0#根据城市的index求出两城市间距离def get_distance(self,index_1,index_2):return distance_list[index_1*city_num+index_2]def get_potency(self,index_1,index_2):return potency_list[index_1*city_num+index_2]def get_prob_list(self):res=[self.get_potency(self.current_city,x)**alpha*(1/self.get_distance(self.current_city,x))**bet a for x in self.cities]sum_=sum(res)final_res=[y/sum_ for y in res]return final_res##轮盘赌选择城市def __choose_next_city(self):city_list=self.citiesprob_list=self.get_prob_list()tmp=random()sum_=0for city,prob in zip(city_list,prob_list):sum_+=probif sum_>=tmp:self.length+=self.get_distance(self.current_city,city)self.current_city=cityself.path.append(self.current_city)self.cities.remove(self.current_city)returndef running(self):global best_length,best_pathfor x in range(city_num-1):self.__choose_next_city()self.length+=self.get_distance(self.current_city,self.initial_city)self.path.append(self.initial_city)if self.length<best_length:best_length=self.lengthbest_path=self.pathreturn (self.path,self.length)def go():operation=[]for x in potency_list:x*=(1-rho)for x in range(ant_num):operation.append(ant(x).running())for x in operation:for y in range(city_num-1):potency_list[x[0][y]*city_num+x[0][y+1]]+=Q/x[1]#print(f"potency_list:{potency_list}")#print(f"best_path:{best_path}")#print(f"best_length:{best_length}")for yy in range(1000):go()print(f"best_length:{best_length}")pu()setpos(x_data[best_path[0]],y_data[best_path[0]])pd()for x in range(1,city_num+1):setpos(x_data[best_path[x]],y_data[best_path[x]]) 运行效果:。

蚁群算法路径优化算法

蚁群算法路径优化算法

其中,表示在t时刻蚂蚁k由元素(城市)i转移到元素(城市)j的状态转移概率。

allowedk = C − tabuk表示蚂蚁k下一步允许选择的城市。

α为启发式因子,表示轨迹的相对重要性,反映了蚂蚁在运动过程中所积累的信息在蚂蚁运动时所起的作用,其值越大,则该蚂蚁越倾向于选择其他蚂蚁经过的路径,蚂蚁之间的协作性越强。

β为期望启发式因子,表示能见度的相对重要性,反映了蚂蚁在运动过程中启发信息在蚂蚁选择路径中的受重视程度,其值越大,则该状态转移概率越接近于贪心规则;ηij(t) 为启发函数,表达式为。

式中,dij表示相邻两个城市之间的距离。

(6)修改禁忌表指针,即选择好之后将蚂蚁移动到新的元素(城市),并把该元素(城市)移动到该蚂蚁个体的禁忌表中。

(7)若集合C中元素(城市)未遍历完,即k<m,则跳转到第(4)步,否则执行第(8)步。

(8)根据公式更新每条路径上的信息量:τij(t + n) = (1 − ρ) * τij(t) + Δτij(t),(9)若满足结束条件,即如果循环次数,则循环结束并输出程序计算结果,否则清空禁忌表并跳转到第(2)步。

蚁群算法的matlab源程序1.蚁群算法主程序:main.m%function [bestroute,routelength]=AntClccleartic% 读入城市间距离矩阵数据文件CooCity = load( 'CooCity.txt' ) ;% 城市网络图坐标数据文件,txt形式给出NC=length(CooCity); % 城市个数for i=1:NC % 计算各城市间的距离for j=1:NCdistance(i,j)=sqrt((CooCity(i,2)-CooCity(j,2))^2+(CooCity(i,3)-CooCity(j,3))^2);endendMAXIT=10;%最大循环次数Citystart=[]; % 起点城市编号tau=ones(NC,NC); % 初始时刻各边上的信息痕迹为1rho=0.5; % 挥发系数alpha=1; % 残留信息相对重要度beta=5; % 预见值的相对重要度Q=10; % 蚁环常数NumAnt=20; % 蚂蚁数量routelength=inf; % 用来记录当前找到的最优路径长度for n=1:MAXITfor k=1:NumAnt %考查第K只蚂蚁deltatau=zeros(NC,NC); % 第K只蚂蚁移动前各边上的信息增量为零%[routek,lengthk]=path(distance,tau,alpha,beta,[]); % 不靠率起始点[routek,lengthk]=path(distance,tau,alpha,beta,Citystart); % 指定起始点if lengthk<routelength %找到一条更好的路径:::routelength=lengthk;:::bestroute=routek;endfor i=1:NC-1 % 第K只蚂蚁在路径上释放的信息量deltatau(routek(i),routek(i+1))=deltatau(routek(i),routek(i+1))+Q/lengthk; % 信息素更新end%deltatau(routek(NC),1)=deltatau(routek(NC),1)+Q/lengthk; %endlength_n(n)=routelength; % 记录路径收敛tau=(1-rho).*tau; % 信息素挥发end%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%costtime=toc;subplot(1,2,1),plot([CooCity(bestroute,2)],[CooCity(bestroute,3)],'-*')subplot(1,2,2),plot([1:MAXIT],length_n,'-*')[routelength,costtime]2.蚁群算法寻找路径程序:path.m% 某只蚂蚁找到的某条路径routek,lengthkfunction [routek,lengthk]=path(distance,tau,alpha,beta,Citystart)[m,n]=size(distance);if isempty(Citystart) % 如果不确定起点p=fix(m*rand)+1; % 随机方式初始化起点,均匀概率elsep=Citystart; % 外部给定确定起点 endlengthk=0; % 初始路径长度设为 0routek=[p]; % 蚂蚁路径点序列,即该蚂蚁已经过的城市集合,路径初始起点for i=1:m-1np=routek(end); % 蚂蚁路径城市序号,依次经过的城市编号np_sum=0; % 路由长度初始为 0for j=1:mif inroute(j,routek) % 判断城市节点j是否属于tabuk,即是否已经过continue;else % j为还未经过的点ada=1/distance(np,j); % 预见度np_sum=np_sum+tau(np,j)^alpha*ada^beta; % 路由表:信息痕迹、预见度 endendcp=zeros(1,m); % 转移概率,基于路径长度及路由表for j=1:mifinroute(j,routek)continue;elseada=1/distance(np,j); % 预见度cp(j)=tau(np,j)^alpha*ada^beta/np_sum; % np到j的转移概率endendNextCity=nextcitychoose2(cp); % 根据转移概率确定下一个城市,% 直观地,取转移概率最大值方向方法,决策结果稳定且收敛快routek=[routek,NextCity]; % 更新路径lengthk=lengthk+distance(np,NextCity); % 更新路径长度end蚁群算法仿真结果:其中左边是蚂蚁行走的最短路径,右边是最短路径的值的收敛情况。

(整理)蚂蚁算法源代码如下

(整理)蚂蚁算法源代码如下

源代码如下:/*ant.c*/#define SPACE 0x20#define ESC 0x1b#define ANT_CHAR_EMPTY '+' #define ANT_CHAR_FOOD 153#define HOME_CHAR 'H'#define FOOD_CHAR 'F'#define FOOD_CHAR2 'f'#define FOOD_HOME_COLOR 12 #define BLOCK_CHAR 177#define MAX_ANT 50#define INI_SPEED 3#define MAXX 80#define MAXY 23#define MAX_FOOD 10000#define TARGET_FOOD 200#define MAX_SMELL 5000#define SMELL_DROP_RATE 0.05 #define ANT_ERROR_RATE 0.02 #define ANT_EYESHOT 3#define SMELL_GONE_SPEED 50 #define SMELL_GONE_RATE 0.05 #define TRACE_REMEMBER 50#define MAX_BLOCK 100#define NULL 0#define UP 1#define DOWN 2#define LEFT 3#define RIGHT 4#define SMELL_TYPE_FOOD 0#define SMELL_TYPE_HOME 1#include "stdio.h"#include "conio.h"#include "dos.h"#include "stdlib.h"#include "dos.h"#include "process.h"#include "ctype.h"#include "math.h"void WorldInitial(void);void BlockInitial(void);void CreatBlock(void);void SaveBlock(void);void LoadBlock(void);void HomeFoodInitial(void);void AntInitial(void);void WorldChange(void);void AntMove(void);void AntOneStep(void);void DealKey(char key);void ClearSmellDisp(void);void DispSmell(int type);int AntNextDir(int xxx,int yyy,int ddir);int GetMaxSmell(int type,int xxx,int yyy,int ddir); int IsTrace(int xxx,int yyy);int MaxLocation(int num1,int num2,int num3);int CanGo(int xxx,int yyy,int ddir);int JudgeCanGo(int xxx,int yyy);int TurnLeft(int ddir);int TurnRight(int ddir);int TurnBack(int ddir);int MainTimer(void);char WaitForKey(int secnum);void DispPlayTime(void);int TimeUse(void);void HideCur(void);void ResetCur(void);/* --------------- */struct HomeStruct{int xxx,yyy;int amount;int TargetFood;}home;struct FoodStruct{int xxx,yyy;int amount;}food;struct AntStruct{int xxx,yyy;int dir;int speed;int SpeedTimer;int food;int SmellAmount[2];int tracex[TRACE_REMEMBER];int tracey[TRACE_REMEMBER];int TracePtr;int IQ;}ant[MAX_ANT];int AntNow;int timer10ms;struct time starttime,endtime;int Smell[2][MAXX+1][MAXY+1];int block[MAXX+1][MAXY+1];int SmellGoneTimer;int SmellDispFlag;int CanFindFood;int HardtoFindPath;/* ----- Main -------- */void main(void){char KeyPress;int tu;clrscr();HideCur();WorldInitial();do{timer10ms = MainTimer();if(timer10ms) AntMove();if(timer10ms) WorldChange();tu = TimeUse();if(tu>=60&&!CanFindFood){gotoxy(1,MAXY+1);printf("Can not find food, maybe a block world.");WaitForKey(10);WorldInitial();}if(tu>=180&&home.amount<100&&!HardtoFindPath){gotoxy(1,MAXY+1);printf("God! it is so difficult to find a path.");if(WaitForKey(10)==0x0d) WorldInitial();else{HardtoFindPath = 1;gotoxy(1,MAXY+1);printf(" ");}}if(home.amount>=home.TargetFood){gettime(&endtime);KeyPress = WaitForKey(60);DispPlayTime();WaitForKey(10);WorldInitial();}else if(kbhit()){KeyPress = getch();DealKey(KeyPress);}else KeyPress = NULL;}while(KeyPress!=ESC);gettime(&endtime);DispPlayTime();WaitForKey(10);clrscr();ResetCur();}/* ------ general sub process ----------- */int MainTimer(void)/* output: how much 10ms have pass from last time call this process */ {static int oldhund,oldsec;struct time t;int timeuse;gettime(&t);timeuse = 0;if(t.ti_hund!=oldhund){if(t.ti_sec!=oldsec){timeuse+=100;oldsec = t.ti_sec;}timeuse+=t.ti_hund-oldhund;oldhund = t.ti_hund;}else timeuse = 0;return (timeuse);}char WaitForKey(int secnum)/* funtion: if have key in, exit immediately, else wait 'secnum' senconds then exitinput: secnum -- wait this senconds, must < 3600 (1 hour)output: key char, if no key in(exit when timeout), return NULL */ {int secin,secnow;int minin,minnow;int hourin,hournow;int secuse;struct time t;gettime(&t);secin = t.ti_sec;minin = t.ti_min;hourin = t.ti_hour;do{if(kbhit()) return(getch());gettime(&t);secnow = t.ti_sec;minnow = t.ti_min;hournow = t.ti_hour;if(hournow!=hourin) minnow+=60;if(minnow>minin) secuse = (minnow-1-minin) + (secnow+60-secin); else secuse = secnow - secin;/* counting error check */if(secuse<0){gotoxy(1,MAXY+1);printf("Time conuting error, any keyto exit...");getch();exit(3);}}while(secuse<=secnum);return (NULL);}void DispPlayTime(void){int ph,pm,ps;ph = endtime.ti_hour - starttime.ti_hour;pm = endtime.ti_min - starttime.ti_min;ps = endtime.ti_sec - starttime.ti_sec;if(ph<0) ph+=24;if(pm<0) { ph--; pm+=60; }if(ps<0) { pm--; ps+=60; }gotoxy(1,MAXY+1);printf("Time use: %d hour- %d min- %d sec ",ph,pm,ps);}int TimeUse(void){int ph,pm,ps;gettime(&endtime);ph = endtime.ti_hour - starttime.ti_hour;pm = endtime.ti_min - starttime.ti_min;ps = endtime.ti_sec - starttime.ti_sec;if(ph<0) ph+=24;if(pm<0) { ph--; pm+=60; }if(ps<0) { pm--; ps+=60; }return(ps+(60*(pm+60*ph)));}void HideCur(void){union REGS regs0;regs0.h.ah=1;regs0.h.ch=0x30;regs0.h.cl=0x31;int86(0x10,&regs0,&regs0);}void ResetCur(void){union REGS regs0;regs0.h.ah=1;regs0.h.ch=0x06;regs0.h.cl=0x07;int86(0x10,&regs0,&regs0);}/* ------------ main ANT programe ------------- */ void WorldInitial(void){int k,i,j;randomize();clrscr();HomeFoodInitial();for(AntNow=0;AntNow<MAX_ANT;AntNow++){AntInitial();} /* of for AntNow */;BlockInitial();for(k=0;k<=1;k++)/* SMELL TYPE FOOD and HOME */for(i=0;i<=MAXX;i++)for(j=0;j<=MAXY;j++)Smell[k][i][j] = 0;SmellGoneTimer = 0;gettime(&starttime);SmellDispFlag = 0;CanFindFood = 0;HardtoFindPath = 0;}void BlockInitial(void){int i,j;int bn;for(i=0;i<=MAXX;i++)for(j=0;j<=MAXY;j++)block[i][j] = 0;bn = 1+ MAX_BLOCK/2 + random(MAX_BLOCK/2);for(i=0;i<=bn;i++) CreatBlock();}void CreatBlock(void){int x1,y1,x2,y2;int dx,dy;int i,j;x1 = random(MAXX)+1;y1 = random(MAXY)+1;dx = random(MAXX/10)+1;dy = random(MAXY/10)+1;x2 = x1+dx;y2 = y1+dy;if(x2>MAXX) x2 = MAXX;if(y2>MAXY) y2 = MAXY;if(food.xxx>=x1&&food.xxx<=x2&&food.yyy>=y1&&food.yyy<=y2) return; if(home.xxx>=x1&&home.xxx<=x2&&home.yyy>=y1&&home.yyy<=y2) return;for(i=x1;i<=x2;i++)for(j=y1;j<=y2;j++){block[i][j] = 1;gotoxy(i,j);putch(BLOCK_CHAR);}}void SaveBlock(void){FILE *fp_block;char FileNameBlock[20];int i,j;gotoxy(1,MAXY+1);printf(" ");gotoxy(1,MAXY+1);printf("Save to file...",FileNameBlock);gets(FileNameBlock);if(FileNameBlock[0]==0) strcpy(FileNameBlock,"Ant.ant"); else strcat(FileNameBlock,".ant");if ((fp_block = fopen(FileNameBlock, "wb")) == NULL){ gotoxy(1,MAXY+1);printf("Creat file %s fail...",FileNameBlock);getch();exit(2);}gotoxy(1,MAXY+1);printf(" ");fputc(home.xxx,fp_block);fputc(home.yyy,fp_block);fputc(food.xxx,fp_block);fputc(food.yyy,fp_block);for(i=0;i<=MAXX;i++)for(j=0;j<=MAXY;j++)fputc(block[i][j],fp_block);fclose(fp_block);}void LoadBlock(void){FILE *fp_block;char FileNameBlock[20];int i,j,k;gotoxy(1,MAXY+1);printf(" ");gotoxy(1,MAXY+1);printf("Load file...",FileNameBlock);gets(FileNameBlock);if(FileNameBlock[0]==0) strcpy(FileNameBlock,"Ant.ant"); else strcat(FileNameBlock,".ant");if ((fp_block = fopen(FileNameBlock, "rb")) == NULL){ gotoxy(1,MAXY+1);printf("Open file %s fail...",FileNameBlock);getch();exit(2);}clrscr();home.xxx = fgetc(fp_block);home.yyy = fgetc(fp_block);food.xxx = fgetc(fp_block);food.yyy = fgetc(fp_block);gotoxy(home.xxx,home.yyy); putch(HOME_CHAR);gotoxy(food.xxx,food.yyy); putch(FOOD_CHAR);food.amount = random(MAX_FOOD/3)+2*MAX_FOOD/3+1;/* food.amount = MAX_FOOD; */home.amount = 0;home.TargetFood =(food.amount<TARGET_FOOD)?food.amount:TARGET_FOOD;for(AntNow=0;AntNow<MAX_ANT;AntNow++){AntInitial();} /* of for AntNow */;for(i=0;i<=MAXX;i++)for(j=0;j<=MAXY;j++){block[i][j] = fgetc(fp_block);if(block[i][j]){gotoxy(i,j);putch(BLOCK_CHAR);}}for(k=0;k<=1;k++)/* SMELL TYPE FOOD and HOME */for(i=0;i<=MAXX;i++)for(j=0;j<=MAXY;j++)Smell[k][i][j] = 0;SmellGoneTimer = 0;gettime(&starttime);SmellDispFlag = 0;CanFindFood = 0;HardtoFindPath = 0;fclose(fp_block);}void HomeFoodInitial(void){int randnum;int homeplace;/* 1 -- home at left-up, food at right-down2 -- home at left-down, food at right-up3 -- home at right-up, food at left-down4 -- home at right-down, food at left-up */randnum = random(100);if(randnum<25) homeplace = 1;else if (randnum>=25&&randnum<50) homeplace = 2; else if (randnum>=50&&randnum<75) homeplace = 3; else homeplace = 4;switch(homeplace){case 1: home.xxx = random(MAXX/3)+1;home.yyy = random(MAXY/3)+1;food.xxx = random(MAXX/3)+2*MAXX/3+1;food.yyy = random(MAXY/3)+2*MAXY/3+1;break;case 2: home.xxx = random(MAXX/3)+1;home.yyy = random(MAXY/3)+2*MAXY/3+1;food.xxx = random(MAXX/3)+2*MAXX/3+1;food.yyy = random(MAXY/3)+1;break;case 3: home.xxx = random(MAXX/3)+2*MAXX/3+1; home.yyy = random(MAXY/3)+1;food.xxx = random(MAXX/3)+1;food.yyy = random(MAXY/3)+2*MAXY/3+1;break;case 4: home.xxx = random(MAXX/3)+2*MAXX/3+1;home.yyy = random(MAXY/3)+2*MAXY/3+1;food.xxx = random(MAXX/3)+1;food.yyy = random(MAXY/3)+1;break;}food.amount = random(MAX_FOOD/3)+2*MAX_FOOD/3+1;/* food.amount = MAX_FOOD; */home.amount = 0;home.TargetFood = (food.amount<TARGET_FOOD)?food.amount:TARGET_FOOD;/* data correctness check */if(home.xxx<=0||home.xxx>MAXX||home.yyy<=0||home.yyy>MAXY||food.xxx<=0||food.xxx>MAXX||food.yyy<=0||food.yyy>MAXY||food.amount<=0){gotoxy(1,MAXY+1);printf("World initial fail, any key to exit...");getch();exit(2);}gotoxy(home.xxx,home.yyy); putch(HOME_CHAR);gotoxy(food.xxx,food.yyy); putch(FOOD_CHAR);}void AntInitial(void)/* initial ant[AntNow] */{int randnum;int i;ant[AntNow].xxx = home.xxx;ant[AntNow].yyy = home.yyy;randnum = random(100);if(randnum<25) ant[AntNow].dir = UP;else if (randnum>=25&&randnum<50) ant[AntNow].dir = DOWN;else if (randnum>=50&&randnum<75) ant[AntNow].dir = LEFT;else ant[AntNow].dir = RIGHT;ant[AntNow].speed = 2*(random(INI_SPEED/2)+1);ant[AntNow].SpeedTimer = 0;ant[AntNow].food = 0;ant[AntNow].SmellAmount[SMELL_TYPE_FOOD] = 0;ant[AntNow].SmellAmount[SMELL_TYPE_HOME] = MAX_SMELL;ant[AntNow].IQ = 1;for(i=0;i<TRACE_REMEMBER;i++){ant[AntNow].tracex[i] = 0;ant[AntNow].tracey[i] = 0;}ant[AntNow].TracePtr = 0;/* a sepecail ant */if(AntNow==0) ant[AntNow].speed = INI_SPEED;}void WorldChange(void){int k,i,j;int smelldisp;SmellGoneTimer+=timer10ms;if(SmellGoneTimer>=SMELL_GONE_SPEED){SmellGoneTimer = 0;for(k=0;k<=1;k++)/* SMELL TYPE FOOD and HOME */for(i=1;i<=MAXX;i++)for(j=1;j<=MAXY;j++){if(Smell[k][i][j]){smelldisp =1+((10*Smell[k][i][j])/(MAX_SMELL*SMELL_DROP_RATE));if(smelldisp>=30000||smelldisp<0) smelldisp = 30000; if(SmellDispFlag){gotoxy(i,j);if((i==food.xxx&&j==food.yyy)||(i==home.xxx&&j==home.yyy))/* don't over write Food and Home */;else{if(smelldisp>9) putch('#');else putch(smelldisp+'0');}}Smell[k][i][j]-= 1+(Smell[k][i][j]*SMELL_GONE_RATE); if(Smell[k][i][j]<0) Smell[k][i][j] = 0;if(SmellDispFlag){if(Smell[k][i][j]<=2){gotoxy(i,j);putch(SPACE);}}}} /* of one location */} /* of time to change the world */} /* of world change */void AntMove(void){int antx,anty;int smelltodrop,smellnow;for(AntNow=0;AntNow<MAX_ANT;AntNow++){ant[AntNow].SpeedTimer+=timer10ms;if(ant[AntNow].SpeedTimer>=ant[AntNow].speed){ant[AntNow].SpeedTimer = 0;gotoxy(ant[AntNow].xxx,ant[AntNow].yyy);putch(SPACE);AntOneStep();gotoxy(ant[AntNow].xxx,ant[AntNow].yyy);/* ant0 is a sepecail ant, use different color */if(AntNow==0) textcolor(0xd);if(ant[AntNow].food) putch(ANT_CHAR_FOOD);else putch(ANT_CHAR_EMPTY);if(AntNow==0) textcolor(0x7);/* remember trace */ant[AntNow].tracex[ant[AntNow].TracePtr] = ant[AntNow].xxx; ant[AntNow].tracey[ant[AntNow].TracePtr] = ant[AntNow].yyy; if(++(ant[AntNow].TracePtr)>=TRACE_REMEMBER)ant[AntNow].TracePtr = 0;/* drop smell */antx = ant[AntNow].xxx;anty = ant[AntNow].yyy;if(ant[AntNow].food)/* have food, looking for home */{if(ant[AntNow].SmellAmount[SMELL_TYPE_FOOD]){smellnow = Smell[SMELL_TYPE_FOOD][antx][anty];smelltodrop =ant[AntNow].SmellAmount[SMELL_TYPE_FOOD]*SMELL_DROP_RATE;if(smelltodrop>smellnow) Smell[SMELL_TYPE_FOOD][antx][anty] = smelltodrop;/* else Smell[...] = smellnow */ant[AntNow].SmellAmount[SMELL_TYPE_FOOD]-= smelltodrop;if(ant[AntNow].SmellAmount[SMELL_TYPE_FOOD]<0)ant[AntNow].SmellAmount[SMELL_TYPE_FOOD] = 0;} /* of have smell to drop */} /* of have food */else/* no food, looking for food */{if(ant[AntNow].SmellAmount[SMELL_TYPE_HOME]){smellnow = Smell[SMELL_TYPE_HOME][antx][anty];smelltodrop =ant[AntNow].SmellAmount[SMELL_TYPE_HOME]*SMELL_DROP_RATE;if(smelltodrop>smellnow) Smell[SMELL_TYPE_HOME][antx][anty] = smelltodrop;/* else Smell[...] = smellnow */ant[AntNow].SmellAmount[SMELL_TYPE_HOME]-= smelltodrop;if(ant[AntNow].SmellAmount[SMELL_TYPE_HOME]<0)ant[AntNow].SmellAmount[SMELL_TYPE_HOME] = 0;} /* of have smell to drop */}} /* of time to go *//* else not go */} /* of for AntNow */textcolor(FOOD_HOME_COLOR);gotoxy(home.xxx,home.yyy); putch(HOME_CHAR);gotoxy(food.xxx,food.yyy);if(food.amount>0) putch(FOOD_CHAR);else putch(FOOD_CHAR2);textcolor(7);gotoxy(1,MAXY+1);printf("Food %d, Home %d ",food.amount,home.amount); }void AntOneStep(void){int ddir,tttx,ttty;int i;ddir = ant[AntNow].dir;tttx = ant[AntNow].xxx;ttty = ant[AntNow].yyy;ddir = AntNextDir(tttx,ttty,ddir);switch(ddir){case UP: ttty--;break;case DOWN: ttty++;break;case LEFT: tttx--;break;case RIGHT: tttx++;break;default: break;} /* of switch dir */ant[AntNow].dir = ddir;ant[AntNow].xxx = tttx;ant[AntNow].yyy = ttty;if(ant[AntNow].food)/* this ant carry with food, search for home */{if(tttx==home.xxx&&ttty==home.yyy){home.amount++;AntInitial();}if(tttx==food.xxx&&ttty==food.yyy)ant[AntNow].SmellAmount[SMELL_TYPE_FOOD] = MAX_SMELL; } /* of search for home */else/* this ant is empty, search for food */{if(tttx==food.xxx&&ttty==food.yyy){if(food.amount>0){ant[AntNow].food = 1;food.amount--;ant[AntNow].SmellAmount[SMELL_TYPE_FOOD] = MAX_SMELL; ant[AntNow].SmellAmount[SMELL_TYPE_HOME] = 0;ant[AntNow].dir = TurnBack(ant[AntNow].dir);for(i=0;i<TRACE_REMEMBER;i++){ant[AntNow].tracex[i] = 0;ant[AntNow].tracey[i] = 0;}ant[AntNow].TracePtr = 0;CanFindFood = 1;} /* of still have food */}if(tttx==home.xxx&&ttty==home.yyy)ant[AntNow].SmellAmount[SMELL_TYPE_HOME] = MAX_SMELL; } /* of search for food */}void DealKey(char key){int i;switch(key){case 'p': gettime(&endtime);DispPlayTime();getch();gotoxy(1,MAXY+1);for(i=1;i<=MAXX-1;i++) putch(SPACE);break;case 't': if(SmellDispFlag){SmellDispFlag=0;ClearSmellDisp();}else SmellDispFlag = 1;break;case '1': DispSmell(SMELL_TYPE_FOOD);getch();ClearSmellDisp();break;case '2': DispSmell(SMELL_TYPE_HOME);getch();ClearSmellDisp();break;case '3': DispSmell(2);getch();ClearSmellDisp();break;case 's': SaveBlock();break;case 'l': LoadBlock();break;default: gotoxy(1,MAXY+1);for(i=1;i<=MAXX-1;i++) putch(SPACE); } /* of switch */}void ClearSmellDisp(void){int k,i,j;for(k=0;k<=1;k++)/* SMELL TYPE FOOD and HOME */for(i=1;i<=MAXX;i++)for(j=1;j<=MAXY;j++){if(Smell[k][i][j]){gotoxy(i,j);putch(SPACE);}} /* of one location */}void DispSmell(int type)/* input: 0 -- Only display food smell1 -- Only display home smell2 -- Display both food and home smell*/{int k,i,j;int fromk,tok;int smelldisp;switch(type){case 0: fromk = 0;tok = 0;break;case 1: fromk = 1;tok = 1;break;case 2: fromk = 0;tok = 1;break;default:fromk = 0;tok = 1;break;}SmellGoneTimer = 0;for(k=fromk;k<=tok;k++)/* SMELL TYPE FOOD and HOME */for(i=1;i<=MAXX;i++)for(j=1;j<=MAXY;j++){if(Smell[k][i][j]){smelldisp =1+((10*Smell[k][i][j])/(MAX_SMELL*SMELL_DROP_RATE));if(smelldisp>=30000||smelldisp<0) smelldisp = 30000; gotoxy(i,j);if(i!=food.xxx||j!=food.yyy){if((i==food.xxx&&j==food.yyy)||(i==home.xxx&&j==home.yyy))/* don't over write Food and Home */;else{if(smelldisp>9) putch('#');else putch(smelldisp+'0');}}}} /* of one location */}int AntNextDir(int xxx,int yyy,int ddir){int randnum;int testdir;int CanGoState;int cangof,cangol,cangor;int msf,msl,msr,maxms;int type;CanGoState = CanGo(xxx,yyy,ddir);if(CanGoState==0||CanGoState==2||CanGoState==3||CanGoState==6) cangof = 1;else cangof = 0;if(CanGoState==0||CanGoState==1||CanGoState==3||CanGoState==5) cangol = 1;else cangol = 0;if(CanGoState==0||CanGoState==1||CanGoState==2||CanGoState==4) cangor = 1;else cangor = 0;if(ant[AntNow].food) type = SMELL_TYPE_HOME;else type = SMELL_TYPE_FOOD;msf = GetMaxSmell(type,xxx,yyy,ddir);msl = GetMaxSmell(type,xxx,yyy,TurnLeft(ddir));msr= GetMaxSmell(type,xxx,yyy,TurnRight(ddir));maxms = MaxLocation(msf,msl,msr);/* maxms - 1 - msf is MAX2 - msl is MAX3 - msr is MAX0 - all 3 number is 0 */testdir = NULL;switch(maxms){case 0: /* all is 0, keep testdir = NULL, random select dir */ break;case 1: if(cangof)testdir = ddir;elseif(msl>msr) if(cangol) testdir = TurnLeft(ddir);else if(cangor) testdir = TurnRight(ddir);break;case 2: if(cangol)testdir = TurnLeft(ddir);elseif(msf>msr) if(cangof) testdir = ddir;else if(cangor) testdir = TurnRight(ddir);break;case 3: if(cangor)testdir = TurnRight(ddir);elseif(msf>msl) if(cangof) testdir =ddir;else if(cangol) testdir = TurnLeft(ddir);break;default:break;} /* of maxms */randnum = random(1000);if(randnum<SMELL_DROP_RATE*1000||testdir==NULL)/* 1. if testdir = NULL, means can not find the max smell or the dir to max smell can not gothen random select dir2. if ant error, don't follow the smell, random select dir*/{randnum = random(100);switch(CanGoState){case 0: if(randnum<90) testdir = ddir;else if (randnum>=90&&randnum<95) testdir = TurnLeft(ddir); else testdir = TurnRight(ddir);break;case 1: if(randnum<50) testdir = TurnLeft(ddir);else testdir = TurnRight(ddir);break;case 2: if(randnum<90) testdir = ddir;else testdir = TurnRight(ddir);break;case 3: if(randnum<90) testdir = ddir;else testdir = TurnLeft(ddir);break;case 4: testdir = TurnRight(ddir);case 5: testdir = TurnLeft(ddir);break;case 6: testdir = ddir;break;case 7: testdir = TurnBack(ddir);break;default:testdir = TurnBack(ddir);} /* of can go state */}return(testdir);}int GetMaxSmell(int type,int xxx,int yyy,int ddir){int i,j;int ms; /* MAX smell */ms = 0;switch(ddir){case UP: for(i=xxx-ANT_EYESHOT;i<=xxx+ANT_EYESHOT;i++) for(j=yyy-ANT_EYESHOT;j<yyy;j++){if(!JudgeCanGo(i,j)) continue;if((i==food.xxx&&j==food.yyy&&type==SMELL_TYPE_FOOD)||(i==home.xxx&&j==home.yyy&&type==SMELL_TYPE_HOME)){ms = MAX_SMELL;break;}if(IsTrace(i,j)) continue;if(Smell[type][i][j]>ms) ms =Smell[type][i][j];}break;case DOWN:for(i=xxx-ANT_EYESHOT;i<=xxx+ANT_EYESHOT;i++)for(j=yyy+1;j<=yyy+ANT_EYESHOT;j++){if(!JudgeCanGo(i,j)) continue;if((i==food.xxx&&j==food.yyy&&type==SMELL_TYPE_FOOD)||(i==home.xxx&&j==home.yyy&&type==SMELL_TYPE_HOME)){ms = MAX_SMELL;break;}if(IsTrace(i,j)) continue;if(Smell[type][i][j]>ms) ms =Smell[type][i][j];}break;case LEFT: for(i=xxx-ANT_EYESHOT;i<xxx;i++)for(j=yyy-ANT_EYESHOT;j<=yyy+ANT_EYESHOT;j++) {if(!JudgeCanGo(i,j)) continue;if((i==food.xxx&&j==food.yyy&&type==SMELL_TYPE_FOOD)||(i==home.xxx&&j==home.yyy&&type==SMELL_TYPE_HOME)){ms = MAX_SMELL;break;}if(IsTrace(i,j)) continue;if(Smell[type][i][j]>ms) ms =Smell[type][i][j];}break;case RIGHT: for(i=xxx+1;i<=xxx+ANT_EYESHOT;i++)for(j=yyy-ANT_EYESHOT;j<=yyy+ANT_EYESHOT;j++) {if(!JudgeCanGo(i,j)) continue;if((i==food.xxx&&j==food.yyy&&type==SMELL_TYPE_FOOD)||(i==home.xxx&&j==home.yyy&&type==SMELL_TYPE_HOME)){ms = MAX_SMELL;break;}if(IsTrace(i,j)) continue;if(Smell[type][i][j]>ms) ms =Smell[type][i][j];}default: break;}return(ms);}int IsTrace(int xxx,int yyy){int i;for(i=0;i<TRACE_REMEMBER;i++)if(ant[AntNow].tracex[i]==xxx&&ant[AntNow].tracey[i]==yyy) return(1);return(0);}int MaxLocation(int num1,int num2,int num3){int maxnum;if(num1==0&&num2==0&&num3==0) return(0);maxnum = num1;if(num2>maxnum) maxnum = num2;if(num3>maxnum) maxnum = num3;if(maxnum==num1) return(1);if(maxnum==num2) return(2);if(maxnum==num3) return(3);}int CanGo(int xxx,int yyy,int ddir)/* input: xxx,yyy - location of antddir - now diroutput: 0 - forward and left and right can go1 - forward can not go2 - left can not go3 - right can not go4 - forward and left can not go5 - forward and right can not go6 - left and right can not go7 - forward and left and right all can not go*/{int tx,ty,tdir;int okf,okl,okr;/* forward can go ? */tdir = ddir;tx = xxx;ty = yyy;switch(tdir){case UP: ty--;break;case DOWN: ty++;break;case LEFT: tx--;break;case RIGHT: tx++;break;default: break;} /* of switch dir */if(JudgeCanGo(tx,ty)) okf = 1; else okf = 0;/* turn left can go ? */tdir = TurnLeft(ddir);tx = xxx;ty = yyy;switch(tdir){case UP: ty--;break;case DOWN: ty++;break;case LEFT: tx--;break;case RIGHT: tx++;break;default: break;} /* of switch dir */if(JudgeCanGo(tx,ty)) okl = 1; else okl = 0;/* turn right can go ? */tdir = TurnRight(ddir);tx = xxx;ty = yyy;switch(tdir){case UP: ty--;break;case DOWN: ty++;break;case LEFT: tx--;break;case RIGHT: tx++;break;default: break;} /* of switch dir */if(JudgeCanGo(tx,ty)) okr = 1; else okr = 0;if(okf&&okl&&okr) return(0);if(!okf&&okl&&okr) return(1);if(okf&&!okl&&okr) return(2);if(okf&&okl&&!okr) return(3);if(!okf&&!okl&&okr) return(4); if(!okf&&okl&&!okr) return(5); if(okf&&!okl&&!okr) return(6); if(!okf&&!okl&&!okr) return(7); return(7);}int JudgeCanGo(int xxx,int yyy) /* input: location to judegoutput: 0 -- can not go1 -- can go*/{int i,j;if(xxx<=0||xxx>MAXX) return(0); if(yyy<=0||yyy>MAXY) return(0); if(block[xxx][yyy]) return(0); return(1);}int TurnLeft(int ddir){switch(ddir){case UP: return(LEFT);case DOWN: return(RIGHT);case LEFT: return(DOWN);case RIGHT: return(UP);default: break;} /* of switch dir */}int TurnRight(int ddir){switch(ddir){case UP: return(RIGHT);case DOWN: return(LEFT);case LEFT: return(UP);case RIGHT: return(DOWN);default: break;} /* of switch dir */}int TurnBack(int ddir){switch(ddir){case UP: return(DOWN);case DOWN: return(UP);case LEFT: return(RIGHT);case RIGHT: return(LEFT);default: break;} /* of switch dir */}小小的蚂蚁总是能够找到食物,他们具有什么样的智能呢?设想,如果我们要为蚂蚁设计一个人工智能的程序,那么这个程序要多么复杂呢?首先,你要让蚂蚁能够避开障碍物,就必须根据适当的地形给它编进指令让他们能够巧妙的避开障碍物,其次,要让蚂蚁找到食物,就需要让他们遍历空间上的所有点;再次,如果要让蚂蚁找到最短的路径,那么需要计算所有可能的路径并且比较它们的大小,而且更重要的是,你要小心翼翼的编程,因为程序的错误也许会让你前功尽弃。

matlab-蚁群算法-机器人路径优化问题

matlab-蚁群算法-机器人路径优化问题

matlab-蚁群算法-机器人路径优化问题4.1问题描述移动机器人路径规划是机器人学的一个重要研究领域。

它要求机器人依据某个或某些优化原则(如最小能量消耗,最短行走路线,最短行走时间等),在其工作空间中找到一条从起始状态到目标状态的能避开障碍物的最优路径。

机器人路径规划问题可以建模为一个有约束的优化问题,都要完成路径规划、定位和避障等任务。

4.2算法理论蚁群算法(AntColonyAlgorithm,ACA),最初是由意大利学者DorigoM.博士于1991年首次提出,其本质是一个复杂的智能系统,且具有较强的鲁棒性,优良的分布式计算机制等优点。

该算法经过十多年的发展,已被广大的科学研究人员应用于各种问题的研究,如旅行商问题,二次规划问题,生产调度问题等。

但是算法本身性能的评价等算法理论研究方面进展较慢。

Dorigo提出了精英蚁群模型(EAS),在这一模型中信息素更新按照得到当前最优解的蚂蚁所构造的解来进行,但这样的策略往往使进化变得缓慢,并不能取得较好的效果。

次年Dorigo博士在文献[30]中给出改进模型(ACS),文中改进了转移概率模型,并且应用了全局搜索与局部搜索策略,来得进行深度搜索。

Stützle与Hoo给出了最大-最小蚂蚁系统(MA某-MINAS),所谓最大-最小即是为信息素设定上限与下限,设定上限避免搜索陷入局部最优,设定下限鼓励深度搜索。

蚂蚁作为一个生物个体其自身的能力是十分有限的,比如蚂蚁个体是没有视觉的,蚂蚁自身体积又是那么渺小,但是由这些能力有限的蚂蚁组成的蚁群却可以做出超越个体蚂蚁能力的超常行为。

蚂蚁没有视觉却可以寻觅食物,蚂蚁体积渺小而蚁群却可以搬运比它们个体大十倍甚至百倍的昆虫。

这些都说明蚂蚁群体内部的某种机制使得它们具有了群体智能,可以做到蚂蚁个体无法实现的事情。

经过生物学家的长时间观察发现,蚂蚁是通过分泌于空间中的信息素进行信息交流,进而实现群体行为的。

蚁群算法matlab代码

蚁群算法matlab代码

蚁群算法matlab代码蚁群算法,英文名为Ant Colony Algorithm,缩写为ACO,是一种启发式算法,是一种模拟蚂蚁寻找食物路径的算法。

在实际生活中,蚂蚁找到食物并返回巢穴后,将其找到食物的路径上的信息素留下,其他蚂蚁通过检测信息素来指导寻路,成为了一种集体智慧行为。

ACO也是通过模拟蚂蚁寻找食物路径的方式来寻找优化问题的最优解。

在ACO算法中,信息素是一个重要的概念,代表了走过某一路径的“好概率”,用这个“好概率”更新一些路径上的信息素,使得其他蚂蚁更可能选择经过这条路径,从而实现路径优化的目的。

在本文中,我们将讨论如何使用Matlab实现蚁群算法来优化问题。

1. 设定问题首先,我们要选取一个优化问题,并将其转换为需要在优化过程中进行选择的决策变量。

例如,我们想要优化旅行商问题(TSP)。

在TSP中,我们需要让旅行商以最短的距离经过所有城市,每个城市仅经过一次,最终回到出发的城市。

我们可以将每个城市编号,然后将TSP转化为一个最短路径选择的问题,即最短路径从编号为1的城市开始,经过所有城市,最终回到编号为1的城市。

2. 设定ACO参数在使用ACO优化问题时,需要设定一些参数,这些参数会影响算法的表现。

ACO算法需要设定的参数有:1.信息素含量:初始信息素的大小,即每个路径上的信息素浓度。

2.信息素挥发速度:信息素的随时间“减弱”程度。

3.信息素加成强度:蚂蚁经过路径后增加的信息素量。

4.启发式权重:用于计算启发式因子,即节点距离的贡献值。

5.蚂蚁数量:模拟蚂蚁数量,即同时寻找路径的蚂蚁个数。

6.迭代次数:模拟的迭代次数,即ACO算法运行的次数。

7.初始节点:ACO算法开始的节点。

3. 创建ACO优化函数我们可以使用Matlab来创建一个函数来实现ACO算法。

我们称其为“ACOoptimization.m”。

function best_path =ACOoptimization(city_location,iter_num,ant_num,init ial_path,alpha,beta,rho,update_flag) %ACO优化函数 %输入: %city_location: 城市坐标矩阵,格式为[x1,y1;x2,y2;...;xn,yn] %iter_num: 迭代次数 %ant_num: 蚂蚁数量 %initial_path: 起始路径,即初始解 %alpha,beta,rho: 超参数,用于调节蚂蚁选择路径的概率 %update_flag: 是否更新信息素的标志(1表示更新,0表示否) %输出: %best_path: 最优解,即最短路径%初始化信息素 pheromone = 0.01 *ones(length(city_location),length(city_location)); %初始化路径权重 path_weight =zeros(ant_num,1); %城市数量 n_cities =length(city_location);%主循环 for iter = 1:iter_num %一个迭代里所有蚂蚁都寻找一遍路径 for ant =1:ant_num %初始化蚂蚁位置current_city = initial_path; %标记是否经过了某个城市 visit_flag =zeros(1,n_cities);visit_flag(current_city) = 1; %用来存储当前路径 current_path = [current_city];%蚂蚁找东西 for i =1:n_cities-1 %计算路径概率p =calculate_probability(current_city,visit_flag,phero mone,city_location,alpha,beta); %蚂蚁选择路径 [next_city,next_index] = select_path(p);%路径更新current_path = [current_path;next_city];visit_flag(next_city) = 1;current_city = next_city;%更新路径权重path_weight(ant) = path_weight(ant) +Euclidean_distance(city_location(current_path(end-1),:),city_location(current_path(end),:));end%加入回到起点的路径权重path_weight(ant) = path_weight(ant) +Euclidean_distance(city_location(current_path(end),:),city_location(current_path(1),:));%判断是否为最优解 ifant == 1 best_path = current_path; else if path_weight(ant) <path_weight(ant-1) best_path =current_path; end end%更新信息素 ifupdate_flag == 1 pheromone =update_pheromone(pheromone,path_weight,initial_path,current_path,rho); end end end end在函数中,我们首先定义了ACOalg函数的参数,包括城市坐标矩阵,迭代次数,蚂蚁数量,初始路径,超参数alpha,beta,rho,以及是否需要更新信息素。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

function [y,val]=QACStic
load att48 att48;
MAXIT=300; % 最大循环次数
NC=48; % 城市个数
tao=ones(48,48);% 初始时刻各边上的信息最为1
rho=0.2; % 挥发系数
alpha=1;
beta=2;
Q=100;
mant=20; % 蚂蚁数量
iter=0; % 记录迭代次数
for i=1:NC % 计算各城市间的距离
for j=1:NC
distance(i,j)=sqrt((att48(i,2)-att48(j,2))^2+(att48(i,3)-att48(j,3))^2);
end
end
bestroute=zeros(1,48); % 用来记录最优路径
routelength=inf; % 用来记录当前找到的最优路径长度
% for i=1:mant % 确定各蚂蚁初始的位置
% end
for ite=1:MAXIT
for ka=1:mant %考查第K只蚂蚁
deltatao=zeros(48,48); % 第K只蚂蚁移动前各边上的信息增量为零
[routek,lengthk]=travel(distance,tao,alpha,beta);
if lengthk<routelength % 找到一条更好的路径
routelength=lengthk;
bestroute=routek;
end
for i=1:NC-1 % 第K只蚂蚁在路径上释放的信息量
deltatao(routek(i),routek(i+1))=deltatao(routek(i),routek(i+1))+Q/lengthk;
end
deltatao(routek(48),1)=deltatao(routek(48),1)+Q/lengthk;
end
for i=1:NC-1
for j=i+1:NC
if deltatao(i,j)==0
deltatao(i,j)=deltatao(j,i);
end
end
end
tao=(1-rho).*tao+deltatao;
end
y=bestroute;
val=routelength;
function [y,val]=travel(distance,tao,alpha,beta) % 某只蚂蚁找到的某条路径
[m,n]=size(distance);
p=fix(m*rand)+1;
val=0; % 初始路径长度设为0
tabuk=[p]; % 假设该蚂蚁都是从第p 个城市出发的
for i=1:m-1
np=tabuk(length(tabuk)); % 蚂蚁当前所在的城市号
p_sum=0;
for j=1:m
if isin(j,tabuk)
continue;
else
ada=1/distance(np,j);
p_sum=p_sum+tao(np,j)^alpha*ada^beta;
end
end
cp=zeros(1,m); % 转移概率
for j=1:m
if isin(j,tabuk)
continue;
else
ada=1/distance(np,j);
cp(j)=tao(np,j)^alpha*ada^beta/p_sum;
end
end
NextCity=pchoice(cp);
tabuk=[tabuk,NextCity];
val=val+distance(np,NextCity);
end
y=tabuk;
function y=isin(x,A) % 判断数x 是否在向量A 中,如在返回1 ,否则返回0 y=0;
for i=1:length(A)
if A(i)==x
y=1;
break;
end
end
function y=pchoice(A)
a=rand;
tempA=zeros(1,length(A)+1); for i=1:length(A)
tempA(i+1)=tempA(i)+A(i); end
for i=2:length(tempA)
if a<=tempA(i)
y=i-1;
break;
end
end。

相关文档
最新文档