1. 什么是基于顺序搜索的动态分区分配算法
动态分区分配算法:
1.首次适应算法(FF/first fit)
2.循环首次适应算法(next fit)
3.最佳适应算法(best fit)
从最小的分区开始分配
4.最坏适应算法(worst fit)
从最大的分区开始分配
5.快速适应算法/分类搜索法(quick fit)
将空闲分区根据其容量的大小进行分类
2. 什么是最优适应分配算法
最佳适应算法是从全部空闲区中找出能满足作业要求的、且大小最小的空闲分区的一种计算方法,这种方法能使碎片尽量小。
最佳适应算法(Best Fit):
它从全部空闲区中找出能满足作业要求的、且大小最小的空闲分区,这种方法能使碎片尽量小。为适应此算法,空闲分区表(空闲区链)中的空闲分区要按从小到大进行排序,自表头开始查找到第一个满足要求的自由分区分配。该算法保留大的空闲区,但造成许多小的空闲区。
Best fit算法等价于装箱问题,举例如下:
装箱问题:有体积为V的箱子N个,体积为Vi的物品M个,求使得物品全部能够装入箱子,箱子数量的最小值。
假设 V=6 N=10,V1,V2,...,V10分别为:3 4 4 3 5 1 2 5 3 1。计算过程如下:
第一步按物品体积降序排序:5 5 4 4 3 3 3 2 1 1
第二步:取未装箱的最大值5装入第一个箱子。
第三步:判断第一个箱子是否已满,不满且剩余空间为1,搜寻剩下体积小于等于1的物品填入箱子1,箱子1填满。
第四步:重复第二,第三步,直到所有物品装入箱子为止,得到箱子数量为6.
6即时本例N的最小值。
3. 同时学现代操作系统、java编程思想、数据库系统概论、flash cs4,firewords cs5、基础医学概论上、4级会疯
让我告诉你如何淡定的解决以上所有课程:
①先买Linux装上,你会发现操作系统很多原始的东西能够感受到,这样学OS,就快了很多,同时操作系统原理边学边写代码,神马银行家算法以及First fit,Best fit,Worst fit等算法都给他写完。
那么 你的《现代操作系统》就搞定了,当你复习题时,会发现,那些题只是浮云,根本逃不出自己的实践演算过程。
每天摸1个小时,保证发现Linux很亲切。
②《Java编程思想》,如果已经学了JAVA,可以看这本书,但是没学的话,就先看另一本《Java2核心技术 卷一:基础卷》这本相当的好,所有开头之前,先把JDK给装上,看每一篇书中代码,就抄上去运行一遍,然后反复调试,对每一篇代码的各种细节的更改就了如指掌。当你JAVA熟练了,它的思想难道不是手到擒来?
当然,最后都学完了,觉得差不多了,花个几个小时或半天写一个小游戏啥的,算是给自己一个交代:“俺能用JAVA开发游戏,俺彻底搞定它了!”
③数据库系统概论,数据库系统难吗?只不过是集合论而已,把你学的每一个概念理清关系并对应到Database Manager 操作中。
最后当然是写一个基于数据库的操作界面,实现比如某个部门的数据管理。
④Flash CS4,Flash很容易学,你把自己当傻子,书怎么说,你就怎么写,比如“请按File->Open....” 你就乖乖那么按,请选中图像后Ctrl+G,你就选中图像Ctrl+G 去组合图像...久而久之,整本书你就自然纯属了。
当然,学会FLASH后还不算学会,没做个复杂的动画咋么能叫学会呢?由于你有编程语言基础了,FLASH ACTIONSCRIPT3.0 你也很快学完了。
这时候,当然是花3-5天左右用FLASH做个简化版超级玛丽出来,你老师会做超级玛丽吗?未必吧(只能说他有用FLASH做出超级玛丽的潜力,但是技术在了,还没集成成作品这完全有区别,做完一遍你的FLASH技术和各种技巧就从理论到实践各个层面上了几个台阶)。
⑤Firework Cs5 ,这东西的学法如同FLASH。
⑥基础医学概论上:学习每一本书都有目的,你把每一页当成一个目的,那么就能串起来学了。
⑦四级,英语四级的话就多看看英文计算机编程书籍,如果是计算机四级,就顺序理论+实践。
4. 如何用Java实现遗传算法
通过遗传算法走迷宫。虽然图1和图2均成功走出迷宫,但是图1比图2的路径长的多,且复杂,遗传算法可以计算出有多少种可能性,并选择其中最简洁的作为运算结果。
示例图1:
实现代码:
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.Iterator;
importjava.util.LinkedList;
importjava.util.List;
importjava.util.Random;
/**
* 用遗传算法走迷宫
*
* @author Orisun
*
*/
publicclassGA {
intgene_len;// 基因长度
intchrom_len;// 染色体长度
intpopulation;// 种群大小
doublecross_ratio;// 交叉率
doublemuta_ratio;// 变异率
intiter_limit;// 最多进化的代数
List<boolean[]> indivials;// 存储当代种群的染色体
Labyrinth labyrinth;
intwidth;//迷宫一行有多少个格子
intheight;//迷宫有多少行
publicclassBI {
doublefitness;
boolean[] indv;
publicBI(doublef,boolean[] ind) {
fitness = f;
indv = ind;
}
publicdoublegetFitness() {
returnfitness;
}
publicboolean[] getIndv() {
returnindv;
}
}
List<BI> best_indivial;// 存储每一代中最优秀的个体
publicGA(Labyrinth labyrinth) {
this.labyrinth=labyrinth;
this.width = labyrinth.map[0].length;
this.height = labyrinth.map.length;
chrom_len =4* (width+height);
gene_len =2;
population =20;
cross_ratio =0.83;
muta_ratio =0.002;
iter_limit =300;
indivials =newArrayList<boolean[]>(population);
best_indivial =newArrayList<BI>(iter_limit);
}
publicintgetWidth() {
returnwidth;
}
publicvoidsetWidth(intwidth) {
this.width = width;
}
publicdoublegetCross_ratio() {
returncross_ratio;
}
publicList<BI> getBest_indivial() {
returnbest_indivial;
}
publicLabyrinth getLabyrinth() {
returnlabyrinth;
}
publicvoidsetLabyrinth(Labyrinth labyrinth) {
this.labyrinth = labyrinth;
}
publicvoidsetChrom_len(intchrom_len) {
this.chrom_len = chrom_len;
}
publicvoidsetPopulation(intpopulation) {
this.population = population;
}
publicvoidsetCross_ratio(doublecross_ratio) {
this.cross_ratio = cross_ratio;
}
publicvoidsetMuta_ratio(doublemuta_ratio) {
this.muta_ratio = muta_ratio;
}
publicvoidsetIter_limit(intiter_limit) {
this.iter_limit = iter_limit;
}
// 初始化种群
publicvoidinitPopulation() {
Random r =newRandom(System.currentTimeMillis());
for(inti =0; i < population; i++) {
intlen = gene_len * chrom_len;
boolean[] ind =newboolean[len];
for(intj =0; j < len; j++)
ind[j] = r.nextBoolean();
indivials.add(ind);
}
}
// 交叉
publicvoidcross(boolean[] arr1,boolean[] arr2) {
Random r =newRandom(System.currentTimeMillis());
intlength = arr1.length;
intslice =0;
do{
slice = r.nextInt(length);
}while(slice ==0);
if(slice < length /2) {
for(inti =0; i < slice; i++) {
booleantmp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = tmp;
}
}else{
for(inti = slice; i < length; i++) {
booleantmp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = tmp;
}
}
}
// 变异
publicvoidmutation(boolean[] indivial) {
intlength = indivial.length;
Random r =newRandom(System.currentTimeMillis());
indivial[r.nextInt(length)] ^=false;
}
// 轮盘法选择下一代,并返回当代最高的适应度值
publicdoubleselection() {
boolean[][] next_generation =newboolean[population][];// 下一代
intlength = gene_len * chrom_len;
for(inti =0; i < population; i++)
next_generation[i] =newboolean[length];
double[] cumulation =newdouble[population];
intbest_index =0;
doublemax_fitness = getFitness(indivials.get(best_index));
cumulation[0] = max_fitness;
for(inti =1; i < population; i++) {
doublefit = getFitness(indivials.get(i));
cumulation[i] = cumulation[i -1] + fit;
// 寻找当代的最优个体
if(fit > max_fitness) {
best_index = i;
max_fitness = fit;
}
}
Random rand =newRandom(System.currentTimeMillis());
for(inti =0; i < population; i++)
next_generation[i] = indivials.get(findByHalf(cumulation,
rand.nextDouble() * cumulation[population -1]));
// 把当代的最优个体及其适应度放到best_indivial中
BI bi =newBI(max_fitness, indivials.get(best_index));
// printPath(indivials.get(best_index));
//System.out.println(max_fitness);
best_indivial.add(bi);
// 新一代作为当前代
for(inti =0; i < population; i++)
indivials.set(i, next_generation[i]);
returnmax_fitness;
}
// 折半查找
publicintfindByHalf(double[] arr,doublefind) {
if(find <0|| find ==0|| find > arr[arr.length -1])
return-1;
intmin =0;
intmax = arr.length -1;
intmedium = min;
do{
if(medium == (min + max) /2)
break;
medium = (min + max) /2;
if(arr[medium] < find)
min = medium;
elseif(arr[medium] > find)
max = medium;
else
returnmedium;
}while(min < max);
returnmax;
}
// 计算适应度
publicdoublegetFitness(boolean[] indivial) {
intlength = indivial.length;
// 记录当前的位置,入口点是(1,0)
intx =1;
inty =0;
// 根据染色体中基因的指导向前走
for(inti =0; i < length; i++) {
booleanb1 = indivial[i];
booleanb2 = indivial[++i];
// 00向左走
if(b1 ==false&& b2 ==false) {
if(x >0&& labyrinth.map[y][x -1] ==true) {
x--;
}
}
// 01向右走
elseif(b1 ==false&& b2 ==true) {
if(x +1< width && labyrinth.map[y][x +1] ==true) {
x++;
}
}
// 10向上走
elseif(b1 ==true&& b2 ==false) {
if(y >0&& labyrinth.map[y -1][x] ==true) {
y--;
}
}
// 11向下走
elseif(b1 ==true&& b2 ==true) {
if(y +1< height && labyrinth.map[y +1][x] ==true) {
y++;
}
}
}
intn = Math.abs(x - labyrinth.x_end) + Math.abs(y -labyrinth.y_end) +1;
// if(n==1)
// printPath(indivial);
return1.0/ n;
}
// 运行遗传算法
publicbooleanrun() {
// 初始化种群
initPopulation();
Random rand =newRandom(System.currentTimeMillis());
booleansuccess =false;
while(iter_limit-- >0) {
// 打乱种群的顺序
Collections.shuffle(indivials);
for(inti =0; i < population -1; i +=2) {
// 交叉
if(rand.nextDouble() < cross_ratio) {
cross(indivials.get(i), indivials.get(i +1));
}
// 变异
if(rand.nextDouble() < muta_ratio) {
mutation(indivials.get(i));
}
}
// 种群更替
if(selection() ==1) {
success =true;
break;
}
}
returnsuccess;
}
// public static void main(String[] args) {
// GA ga = new GA(8, 8);
// if (!ga.run()) {
// System.out.println("没有找到走出迷宫的路径.");
// } else {
// int gen = ga.best_indivial.size();
// boolean[] indivial = ga.best_indivial.get(gen - 1).indv;
// System.out.println(ga.getPath(indivial));
// }
// }
// 根据染色体打印走法
publicString getPath(boolean[] indivial) {
intlength = indivial.length;
intx =1;
inty =0;
LinkedList<String> stack=newLinkedList<String>();
for(inti =0; i < length; i++) {
booleanb1 = indivial[i];
booleanb2 = indivial[++i];
if(b1 ==false&& b2 ==false) {
if(x >0&& labyrinth.map[y][x -1] ==true) {
x--;
if(!stack.isEmpty() && stack.peek()=="右")
stack.poll();
else
stack.push("左");
}
}elseif(b1 ==false&& b2 ==true) {
if(x +1< width && labyrinth.map[y][x +1] ==true) {
x++;
if(!stack.isEmpty() && stack.peek()=="左")
stack.poll();
else
stack.push("右");
}
}elseif(b1 ==true&& b2 ==false) {
if(y >0&& labyrinth.map[y -1][x] ==true) {
y--;
if(!stack.isEmpty() && stack.peek()=="下")
stack.poll();
else
stack.push("上");
}
}elseif(b1 ==true&& b2 ==true) {
if(y +1< height && labyrinth.map[y +1][x] ==true) {
y++;
if(!stack.isEmpty() && stack.peek()=="上")
stack.poll();
else
stack.push("下");
}
}
}
StringBuilder sb=newStringBuilder(length/4);
Iterator<String> iter=stack.descendingIterator();
while(iter.hasNext())
sb.append(iter.next());
returnsb.toString();
}
}
5. best-fit什么意思及同义词
best-fit英 ['bestf'ɪt] 美 ['bestf'ɪt]
[释义][计] 最佳适合,最优满足;
[网络]最优满足; 最佳拟合; 最佳适合;
[例句]This algorithm tends to be a bit more time efficient but can waste
memory e to the best-fit approach.
这个算法的时间效率更高,但是由于使用best-fit方法的缘故,会产生内存浪费。
只有大致相同的词:best for
6. 遗传算法
遗传算法实例:
也是自己找来的,原代码有少许错误,本人都已更正了,调试运行都通过了的。
对于初学者,尤其是还没有编程经验的非常有用的一个文件
遗传算法实例
% 下面举例说明遗传算法 %
% 求下列函数的最大值 %
% f(x)=10*sin(5x)+7*cos(4x) x∈[0,10] %
% 将 x 的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为 (10-0)/(2^10-1)≈0.01 。 %
% 将变量域 [0,10] 离散化为二值域 [0,1023], x=0+10*b/1023, 其中 b 是 [0,1023] 中的一个二值数。 %
% %
%--------------------------------------------------------------------------------------------------------------%
%--------------------------------------------------------------------------------------------------------------%
% 编程
%-----------------------------------------------
% 2.1初始化(编码)
% initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二值数的长度),
% 长度大小取决于变量的二进制编码的长度(在本例中取10位)。
%遗传算法子程序
%Name: initpop.m
%初始化
function pop=initpop(popsize,chromlength)
pop=round(rand(popsize,chromlength)); % rand随机产生每个单元为 {0,1} 行数为popsize,列数为chromlength的矩阵,
% roud对矩阵的每个单元进行圆整。这样产生的初始种群。
% 2.2 计算目标函数值
% 2.2.1 将二进制数转化为十进制数(1)
%遗传算法子程序
%Name: decodebinary.m
%产生 [2^n 2^(n-1) ... 1] 的行向量,然后求和,将二进制转化为十进制
function pop2=decodebinary(pop)
[px,py]=size(pop); %求pop行和列数
for i=1:py
pop1(:,i)=2.^(py-i).*pop(:,i);
end
pop2=sum(pop1,2); %求pop1的每行之和
% 2.2.2 将二进制编码转化为十进制数(2)
% decodechrom.m函数的功能是将染色体(或二进制编码)转换为十进制,参数spoint表示待解码的二进制串的起始位置
% (对于多个变量而言,如有两个变量,采用20为表示,每个变量10为,则第一个变量从1开始,另一个变量从11开始。本例为1),
% 参数1ength表示所截取的长度(本例为10)。
%遗传算法子程序
%Name: decodechrom.m
%将二进制编码转换成十进制
function pop2=decodechrom(pop,spoint,length)
pop1=pop(:,spoint:spoint+length-1);
pop2=decodebinary(pop1);
% 2.2.3 计算目标函数值
% calobjvalue.m函数的功能是实现目标函数的计算,其公式采用本文示例仿真,可根据不同优化问题予以修改。
%遗传算法子程序
%Name: calobjvalue.m
%实现目标函数的计算
function [objvalue]=calobjvalue(pop)
temp1=decodechrom(pop,1,10); %将pop每行转化成十进制数
x=temp1*10/1023; %将二值域 中的数转化为变量域 的数
objvalue=10*sin(5*x)+7*cos(4*x); %计算目标函数值
% 2.3 计算个体的适应值
%遗传算法子程序
%Name:calfitvalue.m
%计算个体的适应值
function fitvalue=calfitvalue(objvalue)
global Cmin;
Cmin=0;
[px,py]=size(objvalue);
for i=1:px
if objvalue(i)+Cmin>0
temp=Cmin+objvalue(i);
else
temp=0.0;
end
fitvalue(i)=temp;
end
fitvalue=fitvalue';
% 2.4 选择复制
% 选择或复制操作是决定哪些个体可以进入下一代。程序中采用赌轮盘选择法选择,这种方法较易实现。
% 根据方程 pi=fi/∑fi=fi/fsum ,选择步骤:
% 1) 在第 t 代,由(1)式计算 fsum 和 pi
% 2) 产生 {0,1} 的随机数 rand( .),求 s=rand( .)*fsum
% 3) 求 ∑fi≥s 中最小的 k ,则第 k 个个体被选中
% 4) 进行 N 次2)、3)操作,得到 N 个个体,成为第 t=t+1 代种群
%遗传算法子程序
%Name: selection.m
%选择复制
function [newpop]=selection(pop,fitvalue)
totalfit=sum(fitvalue); %求适应值之和
fitvalue=fitvalue/totalfit; %单个个体被选择的概率
fitvalue=cumsum(fitvalue); %如 fitvalue=[1 2 3 4],则 cumsum(fitvalue)=[1 3 6 10]
[px,py]=size(pop);
ms=sort(rand(px,1)); %从小到大排列
fitin=1;
newin=1;
while newin<=px
if(ms(newin))<fitvalue(fitin)
newpop(newin)=pop(fitin);
newin=newin+1;
else
fitin=fitin+1;
end
end
% 2.5 交叉
% 交叉(crossover),群体中的每个个体之间都以一定的概率 pc 交叉,即两个个体从各自字符串的某一位置
% (一般是随机确定)开始互相交换,这类似生物进化过程中的基因分裂与重组。例如,假设2个父代个体x1,x2为:
% x1=0100110
% x2=1010001
% 从每个个体的第3位开始交叉,交又后得到2个新的子代个体y1,y2分别为:
% y1=0100001
% y2=1010110
% 这样2个子代个体就分别具有了2个父代个体的某些特征。利用交又我们有可能由父代个体在子代组合成具有更高适合度的个体。
% 事实上交又是遗传算法区别于其它传统优化方法的主要特点之一。
%遗传算法子程序
%Name: crossover.m
%交叉
function [newpop]=crossover(pop,pc)
[px,py]=size(pop);
newpop=ones(size(pop));
for i=1:2:px-1
if(rand<pc)
cpoint=round(rand*py);
newpop(i,:)=[pop(i,1:cpoint),pop(i+1,cpoint+1:py)];
newpop(i+1,:)=[pop(i+1,1:cpoint),pop(i,cpoint+1:py)];
else
newpop(i,:)=pop(i);
newpop(i+1,:)=pop(i+1);
end
end
% 2.6 变异
% 变异(mutation),基因的突变普遍存在于生物的进化过程中。变异是指父代中的每个个体的每一位都以概率 pm 翻转,即由“1”变为“0”,
% 或由“0”变为“1”。遗传算法的变异特性可以使求解过程随机地搜索到解可能存在的整个空间,因此可以在一定程度上求得全局最优解。
%遗传算法子程序
%Name: mutation.m
%变异
function [newpop]=mutation(pop,pm)
[px,py]=size(pop);
newpop=ones(size(pop));
for i=1:px
if(rand<pm)
mpoint=round(rand*py);
if mpoint<=0
mpoint=1;
end
newpop(i)=pop(i);
if any(newpop(i,mpoint))==0
newpop(i,mpoint)=1;
else
newpop(i,mpoint)=0;
end
else
newpop(i)=pop(i);
end
end
% 2.7 求出群体中最大得适应值及其个体
%遗传算法子程序
%Name: best.m
%求出群体中适应值最大的值
function [bestindivial,bestfit]=best(pop,fitvalue)
[px,py]=size(pop);
bestindivial=pop(1,:);
bestfit=fitvalue(1);
for i=2:px
if fitvalue(i)>bestfit
bestindivial=pop(i,:);
bestfit=fitvalue(i);
end
end
% 2.8 主程序
%遗传算法主程序
%Name:genmain05.m
clear
clf
popsize=20; %群体大小
chromlength=10; %字符串长度(个体长度)
pc=0.6; %交叉概率
pm=0.001; %变异概率
pop=initpop(popsize,chromlength); %随机产生初始群体
for i=1:20 %20为迭代次数
[objvalue]=calobjvalue(pop); %计算目标函数
fitvalue=calfitvalue(objvalue); %计算群体中每个个体的适应度
[newpop]=selection(pop,fitvalue); %复制
[newpop]=crossover(pop,pc); %交叉
[newpop]=mutation(pop,pc); %变异
[bestindivial,bestfit]=best(pop,fitvalue); %求出群体中适应值最大的个体及其适应值
y(i)=max(bestfit);
n(i)=i;
pop5=bestindivial;
x(i)=decodechrom(pop5,1,chromlength)*10/1023;
pop=newpop;
end
fplot('10*sin(5*x)+7*cos(4*x)',[0 10])
hold on
plot(x,y,'r*')
hold off
[z index]=max(y); %计算最大值及其位置
x5=x(index)%计算最大值对应的x值
y=z
【问题】求f(x)=x 10*sin(5x) 7*cos(4x)的最大值,其中0<=x<=9
【分析】选择二进制编码,种群中的个体数目为10,二进制编码长度为20,交叉概率为0.95,变异概率为0.08
【程序清单】
%编写目标函数
function[sol,eval]=fitness(sol,options)
x=sol(1);
eval=x 10*sin(5*x) 7*cos(4*x);
%把上述函数存储为fitness.m文件并放在工作目录下
initPop=initializega(10,[0 9],'fitness');%生成初始种群,大小为10
[x endPop,bPop,trace]=ga([0 9],'fitness',[],initPop,[1e-6 1 1],'maxGenTerm',25,'normGeomSelect',...
[0.08],['arithXover'],[2],'nonUnifMutation',[2 25 3]) %25次遗传迭代
运算借过为:x =
7.8562 24.8553(当x为7.8562时,f(x)取最大值24.8553)
注:遗传算法一般用来取得近似最优解,而不是最优解。
遗传算法实例2
【问题】在-5<=Xi<=5,i=1,2区间内,求解
f(x1,x2)=-20*exp(-0.2*sqrt(0.5*(x1.^2 x2.^2)))-exp(0.5*(cos(2*pi*x1) cos(2*pi*x2))) 22.71282的最小值。
【分析】种群大小10,最大代数1000,变异率0.1,交叉率0.3
【程序清单】
%源函数的matlab代码
function [eval]=f(sol)
numv=size(sol,2);
x=sol(1:numv);
eval=-20*exp(-0.2*sqrt(sum(x.^2)/numv)))-exp(sum(cos(2*pi*x))/numv) 22.71282;
%适应度函数的matlab代码
function [sol,eval]=fitness(sol,options)
numv=size(sol,2)-1;
x=sol(1:numv);
eval=f(x);
eval=-eval;
%遗传算法的matlab代码
bounds=ones(2,1)*[-5 5];
[p,endPop,bestSols,trace]=ga(bounds,'fitness')
注:前两个文件存储为m文件并放在工作目录下,运行结果为
p =
0.0000 -0.0000 0.0055
大家可以直接绘出f(x)的图形来大概看看f(x)的最值是多少,也可是使用优化函数来验证。matlab命令行执行命令:
fplot('x 10*sin(5*x) 7*cos(4*x)',[0,9])
evalops是传递给适应度函数的参数,opts是二进制编码的精度,termops是选择maxGenTerm结束函数时传递个maxGenTerm的参数,即遗传代数。xoverops是传递给交叉函数的参数。mutops是传递给变异函数的参数。
【问题】求f(x)=x+10*sin(5x)+7*cos(4x)的最大值,其中0<=x<=9
【分析】选择二进制编码,种群中的个体数目为10,二进制编码长度为20,交叉概率为0.95,变异概率为0.08
【程序清单】
%编写目标函数
function[sol,eval]=fitness(sol,options)
x=sol(1);
eval=x+10*sin(5*x)+7*cos(4*x);
%把上述函数存储为fitness.m文件并放在工作目录下
initPop=initializega(10,[0 9],'fitness');%生成初始种群,大小为10
[x endPop,bPop,trace]=ga([0 9],'fitness',[],initPop,[1e-6 1 1],'maxGenTerm',25,'normGeomSelect',...
[0.08],['arithXover'],[2],'nonUnifMutation',[2 25 3]) %25次遗传迭代
运算借过为:x =
7.8562 24.8553(当x为7.8562时,f(x)取最大值24.8553)
注:遗传算法一般用来取得近似最优解,而不是最优解。
遗传算法实例2
【问题】在-5<=Xi<=5,i=1,2区间内,求解
f(x1,x2)=-20*exp(-0.2*sqrt(0.5*(x1.^2+x2.^2)))-exp(0.5*(cos(2*pi*x1)+cos(2*pi*x2)))+22.71282的最小值。
【分析】种群大小10,最大代数1000,变异率0.1,交叉率0.3
【程序清单】
%源函数的matlab代码
function [eval]=f(sol)
numv=size(sol,2);
x=sol(1:numv);
eval=-20*exp(-0.2*sqrt(sum(x.^2)/numv)))-exp(sum(cos(2*pi*x))/numv)+22.71282;
%适应度函数的matlab代码
function [sol,eval]=fitness(sol,options)
numv=size(sol,2)-1;
x=sol(1:numv);
eval=f(x);
eval=-eval;
%遗传算法的matlab代码
bounds=ones(2,1)*[-5 5];
[p,endPop,bestSols,trace]=ga(bounds,'fitness')
注:前两个文件存储为m文件并放在工作目录下,运行结果为
p =
0.0000 -0.0000 0.0055
大家可以直接绘出f(x)的图形来大概看看f(x)的最值是多少,也可是使用优化函数来验证。matlab命令行执行命令:
fplot('x+10*sin(5*x)+7*cos(4*x)',[0,9])
evalops是传递给适应度函数的参数,opts是二进制编码的精度,termops是选择maxGenTerm结束函数时传递个maxGenTerm的参数,即遗传代数。xoverops是传递给交叉函数的参数。mutops是传递给变异函数的参数。
打字不易,如满意,望采纳。
7. java人工蜂群算法求解TSP问题
一、人工蜂群算法的介绍
人工蜂群算法(Artificial Bee Colony, ABC)是由Karaboga于2005年提出的一种新颖的基于群智能的全局优化算法,其直观背景来源于蜂群的采蜜行为,蜜蜂根据各自的分工进行不同的活动,并实现蜂群信息的共享和交流,从而找到问题的最优解。人工蜂群算法属于群智能算法的一种。
二、人工蜂群算法的原理
1、原理
标准的ABC算法通过模拟实际蜜蜂的采蜜机制将人工蜂群分为3类: 采蜜蜂、观察蜂和侦察蜂。整个蜂群的目标是寻找花蜜量最大的蜜源。在标准的ABC算法中,采蜜蜂利用先前的蜜源信息寻找新的蜜源并与观察蜂分享蜜源信息;观察蜂在蜂房中等待并依据采蜜蜂分享的信息寻找新的蜜源;侦查蜂的任务是寻找一个新的有价值的蜜源,它们在蜂房附近随机地寻找蜜源。
假设问题的解空间是。
代码:
[cpp]view plain
#include<iostream>
#include<time.h>
#include<stdlib.h>
#include<cmath>
#include<fstream>
#include<iomanip>
usingnamespacestd;
constintNP=40;//种群的规模,采蜜蜂+观察蜂
constintFoodNumber=NP/2;//食物的数量,为采蜜蜂的数量
constintlimit=20;//限度,超过这个限度没有更新采蜜蜂变成侦查蜂
constintmaxCycle=10000;//停止条件
/*****函数的特定参数*****/
constintD=2;//函数的参数个数
constdoublelb=-100;//函数的下界
constdoubleub=100;//函数的上界
doubleresult[maxCycle]={0};
/*****种群的定义****/
structBeeGroup
{
doublecode[D];//函数的维数
doubletrueFit;//记录真实的最小值
doublefitness;
doublerfitness;//相对适应值比例
inttrail;//表示实验的次数,用于与limit作比较
}Bee[FoodNumber];
BeeGroupNectarSource[FoodNumber];//蜜源,注意:一切的修改都是针对蜜源而言的
BeeGroupEmployedBee[FoodNumber];//采蜜蜂
BeeGroupOnLooker[FoodNumber];//观察蜂
BeeGroupBestSource;//记录最好蜜源
/*****函数的声明*****/
doublerandom(double,double);//产生区间上的随机数
voidinitilize();//初始化参数
doublecalculationTruefit(BeeGroup);//计算真实的函数值
doublecalculationFitness(double);//计算适应值
voidCalculateProbabilities();//计算轮盘赌的概率
voidevalueSource();//评价蜜源
voidsendEmployedBees();
voidsendOnlookerBees();
voidsendScoutBees();
voidMemorizeBestSource();
/*******主函数*******/
intmain()
{
ofstreamoutput;
output.open("dataABC.txt");
srand((unsigned)time(NULL));
initilize();//初始化
MemorizeBestSource();//保存最好的蜜源
//主要的循环
intgen=0;
while(gen<maxCycle)
{
sendEmployedBees();
CalculateProbabilities();
sendOnlookerBees();
MemorizeBestSource();
sendScoutBees();
MemorizeBestSource();
output<<setprecision(30)<<BestSource.trueFit<<endl;
gen++;
}
output.close();
cout<<"运行结束!!"<<endl;
return0;
}
/*****函数的实现****/
doublerandom(doublestart,doubleend)//随机产生区间内的随机数
{
returnstart+(end-start)*rand()/(RAND_MAX+1.0);
}
voidinitilize()//初始化参数
{
inti,j;
for(i=0;i<FoodNumber;i++)
{
for(j=0;j<D;j++)
{
NectarSource[i].code[j]=random(lb,ub);
EmployedBee[i].code[j]=NectarSource[i].code[j];
OnLooker[i].code[j]=NectarSource[i].code[j];
BestSource.code[j]=NectarSource[0].code[j];
}
/****蜜源的初始化*****/
NectarSource[i].trueFit=calculationTruefit(NectarSource[i]);
NectarSource[i].fitness=calculationFitness(NectarSource[i].trueFit);
NectarSource[i].rfitness=0;
NectarSource[i].trail=0;
/****采蜜蜂的初始化*****/
EmployedBee[i].trueFit=NectarSource[i].trueFit;
EmployedBee[i].fitness=NectarSource[i].fitness;
EmployedBee[i].rfitness=NectarSource[i].rfitness;
EmployedBee[i].trail=NectarSource[i].trail;
/****观察蜂的初始化****/
OnLooker[i].trueFit=NectarSource[i].trueFit;
OnLooker[i].fitness=NectarSource[i].fitness;
OnLooker[i].rfitness=NectarSource[i].rfitness;
OnLooker[i].trail=NectarSource[i].trail;
}
/*****最优蜜源的初始化*****/
BestSource.trueFit=NectarSource[0].trueFit;
BestSource.fitness=NectarSource[0].fitness;
BestSource.rfitness=NectarSource[0].rfitness;
BestSource.trail=NectarSource[0].trail;
}
doublecalculationTruefit(BeeGroupbee)//计算真实的函数值
{
doubletruefit=0;
/******测试函数1******/
truefit=0.5+(sin(sqrt(bee.code[0]*bee.code[0]+bee.code[1]*bee.code[1]))*sin(sqrt(bee.code[0]*bee.code[0]+bee.code[1]*bee.code[1]))-0.5)
/((1+0.001*(bee.code[0]*bee.code[0]+bee.code[1]*bee.code[1]))*(1+0.001*(bee.code[0]*bee.code[0]+bee.code[1]*bee.code[1])));
returntruefit;
}
doublecalculationFitness(doubletruefit)//计算适应值
{
doublefitnessResult=0;
if(truefit>=0)
{
fitnessResult=1/(truefit+1);
}else
{
fitnessResult=1+abs(truefit);
}
returnfitnessResult;
}
voidsendEmployedBees()//修改采蜜蜂的函数
{
inti,j,k;
intparam2change;//需要改变的维数
doubleRij;//[-1,1]之间的随机数
for(i=0;i<FoodNumber;i++)
{
param2change=(int)random(0,D);//随机选取需要改变的维数
/******选取不等于i的k********/
while(1)
{
k=(int)random(0,FoodNumber);
if(k!=i)
{
break;
}
}
for(j=0;j<D;j++)
{
EmployedBee[i].code[j]=NectarSource[i].code[j];
}
/*******采蜜蜂去更新信息*******/
Rij=random(-1,1);
EmployedBee[i].code[param2change]=NectarSource[i].code[param2change]+Rij*(NectarSource[i].code[param2change]-NectarSource[k].code[param2change]);
/*******判断是否越界********/
if(EmployedBee[i].code[param2change]>ub)
{
EmployedBee[i].code[param2change]=ub;
}
if(EmployedBee[i].code[param2change]<lb)
{
EmployedBee[i].code[param2change]=lb;
}
EmployedBee[i].trueFit=calculationTruefit(EmployedBee[i]);
EmployedBee[i].fitness=calculationFitness(EmployedBee[i].trueFit);
/******贪婪选择策略*******/
if(EmployedBee[i].trueFit<NectarSource[i].trueFit)
{
for(j=0;j<D;j++)
{
NectarSource[i].code[j]=EmployedBee[i].code[j];
}
NectarSource[i].trail=0;
NectarSource[i].trueFit=EmployedBee[i].trueFit;
NectarSource[i].fitness=EmployedBee[i].fitness;
}else
{
NectarSource[i].trail++;
}
}
}
voidCalculateProbabilities()//计算轮盘赌的选择概率
{
inti;
doublemaxfit;
maxfit=NectarSource[0].fitness;
for(i=1;i<FoodNumber;i++)
{
if(NectarSource[i].fitness>maxfit)
maxfit=NectarSource[i].fitness;
}
for(i=0;i<FoodNumber;i++)
{
NectarSource[i].rfitness=(0.9*(NectarSource[i].fitness/maxfit))+0.1;
}
}
voidsendOnlookerBees()//采蜜蜂与观察蜂交流信息,观察蜂更改信息
{
inti,j,t,k;
doubleR_choosed;//被选中的概率
intparam2change;//需要被改变的维数
doubleRij;//[-1,1]之间的随机数
i=0;
t=0;
while(t<FoodNumber)
{
R_choosed=random(0,1);
if(R_choosed<NectarSource[i].rfitness)//根据被选择的概率选择
{
t++;
param2change=(int)random(0,D);
/******选取不等于i的k********/
while(1)
{
k=(int)random(0,FoodNumber);
if(k!=i)
{
break;
}
}
for(j=0;j<D;j++)
{
OnLooker[i].code[j]=NectarSource[i].code[j];
}
/****更新******/
Rij=random(-1,1);
OnLooker[i].code[param2change]=NectarSource[i].code[param2change]+Rij*(NectarSource[i].code[param2change]-NectarSource[k].code[param2change]);
/*******判断是否越界*******/
if(OnLooker[i].code[param2change]<lb)
{
OnLooker[i].code[param2change]=lb;
}
if(OnLooker[i].code[param2change]>ub)
{
OnLooker[i].code[param2change]=ub;
}
OnLooker[i].trueFit=calculationTruefit(OnLooker[i]);
OnLooker[i].fitness=calculationFitness(OnLooker[i].trueFit);
/****贪婪选择策略******/
if(OnLooker[i].trueFit<NectarSource[i].trueFit)
{
for(j=0;j<D;j++)
{
NectarSource[i].code[j]=OnLooker[i].code[j];
}
NectarSource[i].trail=0;
NectarSource[i].trueFit=OnLooker[i].trueFit;
NectarSource[i].fitness=OnLooker[i].fitness;
}else
{
NectarSource[i].trail++;
}
}
i++;
if(i==FoodNumber)
{
i=0;
}
}
}
8. 页面置换算法的实验
#include <stdio.h>
#define PROCESS_NAME_LEN 32 /*进程名称的最大长度*/
#define MIN_SLICE 10 /*最小碎片的大小*/
#define DEFAULT_MEM_SIZE 1024 /*默认内存的大小*/
#define DEFAULT_MEM_START 0 /*默认内存的起始位置*/
/* 内存分配算法 */
#define MA_FF 1
#define MA_BF 2
#define MA_WF 3
int mem_size=DEFAULT_MEM_SIZE; /*内存大小*/
int ma_algorithm = MA_FF; /*当前分配算法*/
static int pid = 0; /*初始pid*/
int flag = 0; /*设置内存大小标志*/
struct free_block_type
{
int size;
int start_addr;
struct free_block_type *next;
};
struct free_block_type *free_block;
struct allocated_block
{
int pid;
int size;
int start_addr;
char process_name[PROCESS_NAME_LEN];
struct allocated_block *next;
};
struct allocated_block *allocated_block_head;
/*初始化空闲块,默认为一块,可以指定大小及起始地址*/
struct free_block_type* init_free_block(int mem_size)
{
struct free_block_type *fb;
fb=(struct free_block_type *)malloc(sizeof(struct free_block_type));
if(fb==NULL)
{
printf("No mem\n");
return NULL;
}
fb->size = mem_size;
fb->start_addr = DEFAULT_MEM_START;
fb->next = NULL;
return fb;
}
void display_menu()
{
printf("\n");
printf("1 - Set memory size (default=%d)\n", DEFAULT_MEM_SIZE);
printf("2 - Select memory allocation algorithm\n");
printf("3 - New process \n");
printf("4 - Terminate a process \n");
printf("5 - Display memory usage \n");
printf("0 - Exit\n");
}
/*设置内存的大小*/
int set_mem_size()
{
int size;
if(flag!=0)
{ /*防止重复设置*/
printf("Cannot set memory size again\n");
return 0;
}
printf("Total memory size =");
scanf("%d", &size);
if(size>0)
{
mem_size = size;
free_block->size = mem_size;
}
flag=1;
return 1;
}
/*Best-fit使用最小的能够放下将要存放数据的块,First-first使用第一个能够放下将要存放数据的块,Worst-fit使用最大的能够放下将要存放数据的块。*/
/* 设置当前的分配算法 */
/*分区分配算法(Partitioning Placement Algorithm)
*/
void set_algorithm()
{
int algorithm;
printf("\t1 - First Fit\n");/*首次适应算法(FF):。 */
printf("\t2 - Best Fit\n");/*最佳适应算法(BF): */
printf("\t3 - Worst Fit\n");
scanf("%d", &algorithm);
if(algorithm>=1 && algorithm <=3) ma_algorithm=algorithm;
/*按指定算法重新排列空闲区链表*/
rearrange(ma_algorithm);
}
void swap(int* data_1,int* data_2)
{
int temp;
temp=*data_1;
*data_1=*data_2;
*data_2=temp;
}
void rearrange_FF()
{
struct free_block_type *tmp, *work;
printf("Rearrange free blocks for FF \n");
tmp = free_block;
while(tmp!=NULL)
{
work = tmp->next;
while(work!=NULL)
{
if( work->start_addr < tmp->start_addr)
{ /*地址递增*/
swap(&work->start_addr, &tmp->start_addr);
swap(&work->size, &tmp->size);
}
else
{
work=work->next;
}
}
tmp=tmp->next;
}
}
/*按BF算法重新整理内存空闲块链表(未完成)
void rearrange_BF()
{
struct free_block_type *tmp,*work;
printf("Rearrange free blocks for BF\n");
tmp=free_block;
while(tmp!=NULL)
{
work=tmp->next;
while(work!=NULL)
{
}
}
}
*/
/*按WF算法重新整理内存空闲块链表(未完成)
void rearrange_WF()
{
struct free_block_type *tmp,*work;
printf("Rearrange free blocks for WF \n");
tmp=free_block;
while(tmp!=NULL)
{
work=tmp->next;
while(work!=NULL)
{
}
}
}
*/
/*按指定的算法整理内存空闲块链表*/
int rearrange(int algorithm)
{
switch(algorithm)
{
case MA_FF: rearrange_FF(); break;
/*case MA_BF: rearrange_BF(); break; */
/*case MA_WF: rearrange_WF(); break; */
}
}
/*创建新的进程,主要是获取内存的申请数量*/
int new_process()
{
struct allocated_block *ab;
int size;
int ret;
ab=(struct allocated_block *)malloc(sizeof(struct allocated_block));
if(!ab)
exit(-5);
ab->next = NULL;
pid++;
sprintf(ab->process_name, "PROCESS-%02d", pid);
ab->pid = pid;
printf("Memory for %s:", ab->process_name);
scanf("%d", &size);
if(size>0) ab->size=size;
ret = allocate_mem(ab); /* 从空闲区分配内存,ret==1表示分配ok*/
/*如果此时allocated_block_head尚未赋值,则赋值*/
if((ret==1) &&(allocated_block_head == NULL))
{
allocated_block_head=ab;
return 1;
}
/*分配成功,将该已分配块的描述插入已分配链表*/
else if (ret==1)
{
ab->next=allocated_block_head;
allocated_block_head=ab;
return 2;
}
else if(ret==-1)
{ /*分配不成功*/
printf("Allocation fail\n");
free(ab);
return -1;
}
return 3;
}
/*分配内存模块*/
int allocate_mem(struct allocated_block *ab)
{
struct free_block_type *fbt,*pre,*r;
int request_size=ab->size;
fbt=pre=free_block;
while(fbt!=NULL)
{
if(fbt->size>=request_size)
{
if(fbt->size-request_size>=MIN_SLICE)
{
fbt->size=fbt->size-request_size;
}
/*分配后空闲空间足够大,则分割*/
else
{
r=fbt;
pre->next=fbt->next;
free(r);
/*分割后空闲区成为小碎片,一起分配*/
return 1;
}
}
pre = fbt;
fbt = fbt->next;
}
return -1;
}
/*将ab所表示的已分配区归还,并进行可能的合并*/
int free_mem(struct allocated_block *ab)
{
int algorithm = ma_algorithm;
struct free_block_type *fbt, *pre, *work;
fbt=(struct free_block_type*) malloc(sizeof(struct free_block_type));
if(!fbt)
return -1;
fbt->size = ab->size;
fbt->start_addr = ab->start_addr;
/*插入到空闲区链表的头部并将空闲区按地址递增的次序排列*/
fbt->next = free_block;
free_block=fbt;
rearrange(MA_FF);
fbt=free_block;
while(fbt!=NULL)
{
work = fbt->next;
if(work!=NULL)
{
/*如果当前空闲区与后面的空闲区相连,则合并*/
if(fbt->start_addr+fbt->size == work->start_addr)
{
fbt->size += work->size;
fbt->next = work->next;
free(work);
continue;
}
}
fbt = fbt->next;
}
rearrange(algorithm); /*重新按当前的算法排列空闲区*/
return 1;
}
/*?释放ab数据结构节点*/
int dispose(struct allocated_block *free_ab)
{
struct allocated_block *pre, *ab;
if(free_ab == allocated_block_head)
{ /*如果要释放第一个节点*/
allocated_block_head = allocated_block_head->next;
free(free_ab);
return 1;
}
pre = allocated_block_head;
ab = allocated_block_head->next;
while(ab!=free_ab)
{
pre = ab;
ab = ab->next;
}
pre->next = ab->next;
free(ab);
return 2;
}
/*查找要删除的进程*/
struct allocated_block* find_process(int pid)
{
struct allocated_block *temp;
temp=allocated_block_head;
while(temp!=NULL)
{
if(temp->pid==pid)
{
return temp;
}
temp=temp->next;
}
}
/*删除进程,归还分配的存储空间,并删除描述该进程内存分配的节点*/
void kill_process()
{
struct allocated_block *ab;
int pid;
printf("Kill Process, pid=");
scanf("%d", &pid);
ab=find_process(pid);
if(ab!=NULL)
{
free_mem(ab); /*释放ab所表示的分配区*/
dispose(ab); /*释放ab数据结构节点*/
}
}
/* 显示当前内存的使用情况,包括空闲区的情况和已经分配的情况 */
int display_mem_usage()
{
struct free_block_type *fbt=free_block;
struct allocated_block *ab=allocated_block_head;
if(fbt==NULL) return(-1);
printf("----------------------------------------------------------\n");
/* 显示空闲区 */
printf("Free Memory:\n");
printf("%20s %20s\n", " start_addr", " size");
while(fbt!=NULL)
{
printf("%20d %20d\n", fbt->start_addr, fbt->size);
fbt=fbt->next;
}
/* 显示已分配区 */
printf("\nUsed Memory:\n");
printf("%10s %20s %10s %10s\n", "PID", "ProcessName", "start_addr", " size");
while(ab!=NULL)
{
printf("%10d %20s %10d %10d\n", ab->pid, ab->process_name, ab->start_addr, ab->size);
ab=ab->next;
}
printf("----------------------------------------------------------\n");
return 0;
}
**********************************************************************
楼主啊,小女子给你的是残缺版滴,要是你给我分,我就把剩下滴给你,上次在北京大学贴吧都被人骗了,世道炎凉啊O(∩_∩)O~
9. 动态分区分配的算法有哪些
动态分区分配算法:
1.首次适应算法(FF/first fit)
2.循环首次适应算法(next fit)
3.最佳适应算法(best fit)
从最小的分区开始分配
4.最坏适应算法(worst fit)
从最大的分区开始分配
5.快速适应算法/分类搜索法(quick fit)
将空闲分区根据其容量的大小进行分类
10. 设计一个实现适应算法的程序
#include <IOSTREAM.H>
#include <STDLIB.H>
typedef struct LNode
{ int size; //内存大小
int state; //0表示空闲,1表示已经装入作业
char task_name; //装入的作业名称
struct LNode *next;
}LNode,*memoryspace;
void Init(memoryspace &L,int size); //初始化空间段
void choice(memoryspace &L); //选择操作类型
void Add(memoryspace &L); //添加作业
void Display(const memoryspace L); //显示作业
void deltask(const memoryspace L); //删除作业
void setfree(memoryspace &L); //回收空闲空间
void main()
{
memoryspace L=new LNode; //memoryspace
int N;
cout<<"初始多大空间,请输入一个整数:"<<ENDL; cin>>N;
Init(L,N); //初始化大小为1000的内存空间
choice(L); //进入操作
}
void Init(memoryspace &L,int size) //初始化空间段
{
memoryspace p = new LNode;
p->size = size;
p->state = 0;
p->task_name = 'n';
p->next = NULL;
L->next = p;
}
void setfree(memoryspace &L) //找出连续的空闲资源,回收空闲空间
{
memoryspace p=L->next,q=p->next;
while(p && q)
{
if(p->state == 0 && q->state == 0) //如果空间连续,则回收
{
p->size +=q->size;
p->next = p->next->next;
delete q;
q=p->next;
}
else
{
p = q;
q = q->next;
}
}
cout<<"回收成功"<<ENDL; cin cout<<?请输入需要回收的作业名称:?; Display(L); flag="0;" int task_name; char { 删除作业 L) memoryspace deltask(const void }>>task_name;
memoryspace p=L,q=L->next;
while(q)
{
if(q->task_name == task_name)
{
q->state=0;
q->task_name='?';
flag=1;
break;
}
else
{
p = q;
q = q->next; //找到要删除作业的下一个结点
}
}
if(flag == 0)
cout<<"删除作业不成功"<<ENDL; int { L) memoryspace void } p="L-" count="1;" 显示作业 Display(const cout<<?删除作业成功?<<endl; else>next;
cout<<"结点号 作业 状态 大小"<<ENDL; { ?<<p- cout<<?结点?<<count<<? while(p)>>new_name;
cout<<"请输入新任务的大小:";
cin>>new_size;
while(p) //查找空闲资源进行分配
{
if (new_size<=0)
{
cout<<ENDL<<"申请的空间不能小于1"<<ENDL; } if(p- break;>state==0 && p->size >= new_size)
{
//
memoryspace q = new LNode;
q->size = p->size - new_size;
q->state = 0;
q->task_name='?';
q->next=NULL;
//
p->size = new_size;
p->state = 1;
p->task_name=new_name;
q->next = p->next;
p->next = q;
break; //分配完成便退出
}
else
{
p = p->next; //移动到足够分配的空结点
}
if(!p)
{
cout<<"作业"<<NEW_NAME<<"内存分配不成功"<<ENDL; } p="L-" break;>next;
while(p) //删除大小为0的结点,当分配空间完时会出现0结点
{
if(p->size == 0)
{
q->next = q->next->next;
delete p;
p = q->next;
}
else
{
q = p;
p = p->next;
}
}
}
void choice(memoryspace &L) //选择操作类型
{
int choice;
do
{
cout<<"0.退出本程序"<<ENDL; cin cout<<endl<<?输入你的选择:?; cout<<?4.回收空闲空间?<<endl; cout<<?3.删除一条作业?<<endl; cout<<?2.显示当前作业?<<endl; cout<<?1.添加新的作业?<<endl;>>choice;
switch(choice)
{
case 0:
exit(1);break;
case 1:
Add(L); break;
case 2:
Display(L); break;
case 3:
deltask(L); break;
case 4:
setfree(L); break;
default:
cout<<"请输入正确的选择!"<<ENDL; } break; pre < choice!="3" || !="2" choice ||choice!="1" }while(choice!="0" cout<<endl;>
<SCRIPT src="/inc/gg_read2.js"></SCRIPT>CRIPT>
//从空闲区分配空间
if(itfreetmp->partionlen==joblen)
{
freetable.erase(itfreetmp);
}
else
{
itfreetmp->baseaddr=itfreetmp->baseaddr+joblen;
itfreetmp->partionlen=itfreetmp->partionlen-joblen;
}
cout<<"为作业"<<jobname<<"分配内存成功!"<<endl;
return;
}
else
{
cout<<"内存不足,为作业分配内存失败!"<<endl;
return;
}
}
void ReclaimMem(string jobname)//回收作业jobname所占的内存
{
list<usedpartion>::iterator itused=usedtable.begin();
list<freepartion>::iterator itfree=freetable.begin();
freepartion free;
while(itused!=usedtable.end())
{
if(itused->jobname==jobname)//找到要回收的作业
{
free.baseaddr=itused->baseaddr;
free.partionlen=itused->partionlen;
usedtable.erase(itused);
if(itfree!=freetable.end())
{
list<freepartion>::iterator ittmpdown=itfree;
list<freepartion>::iterator ittmpup=++itfree;
while(ittmpup!=freetable.end())
{
if(free.baseaddr==(ittmpdown->baseaddr+ittmpdown->partionlen))//下邻空闲区
{
if(free.baseaddr+free.partionlen==ittmpup->baseaddr)//下邻空闲区,上邻空闲区
{
ittmpdown->partionlen=ittmpdown->partionlen+free.partionlen+ittmpup->partionlen;
freetable.erase(ittmpup);//删除上邻空闲区
cout<<"回收作业所占的内存成功!"<<endl;
return;
}
else//下邻空闲区,但不上邻空闲区
{
ittmpdown->partionlen=ittmpdown->partionlen+free.partionlen;
cout<<"回收作业所占的内存成功!"<<endl;
return;
}
}
else if(free.baseaddr+free.partionlen==ittmpup->baseaddr)//上邻空闲区,但不下邻空闲区
{
ittmpup->baseaddr=free.baseaddr;
ittmpup->partionlen=free.partionlen+ittmpup->partionlen;
cout<<"回收作业所占的内存成功!"<<endl;
return;
}
else//既不下邻空闲区又不上邻空闲区
{
if((free.baseaddr<ittmpup->baseaddr)&&(free.baseaddr>ittmpdown->baseaddr)) {
freetable.insert(ittmpup,free);
cout<<"回收作业所占的内存成功!"<<endl;
return;
}
else
{
if(free.baseaddr<ittmpdown->baseaddr)//小于空闲区下限
{
freetable.insert(ittmpdown,free);
cout<<"回收作业所占的内存成功!"<<endl;
return;
}
else//大于空闲区上限
{
ittmpdown=ittmpup;
itfree++;
ittmpup=itfree;
continue;
}
}//
}//else既不下邻空闲区又不上邻空闲区
}//while
if(ittmpup==freetable.end())
{
if(ittmpdown->baseaddr>free.baseaddr)
{
if(free.baseaddr+free.partionlen==ittmpdown->baseaddr)//上邻空闲区
{
ittmpdown->baseaddr=free.baseaddr;
ittmpdown->partionlen=ittmpdown->partionlen+free.partionlen;
cout<<"回收作业所占的内存成功!"<<endl;
return;
}
else//不上邻空闲区
{
freetable.insert(ittmpdown,free);
cout<<"回收作业所占的内存成功!"<<endl;
return;
}
}
else
{
if(ittmpdown->baseaddr+ittmpdown->partionlen==free.baseaddr)//下邻空闲区
{
ittmpdown->partionlen=ittmpdown->partionlen+free.partionlen;
cout<<"回收作业所占的内存成功!"<<endl;
return;
}
else
{
freetable.push_back(free);
cout<<"回收作业所占的内存成功!"<<endl;
return;
}
}
}//if(ittmpup==freetable.end())
/*else//没有遍历到空闲区表的末尾就已更新表
{
cout<<"回收作业所占的内存成功!"<<endl;
return;
}*/
}//if(itfree!=NULL)
else//空闲分区表为空
{
freetable.push_back(free);
cout<<"回收作业所占的内存成功!"<<endl;
return;
}
}//if(itused...)
else //未找到要回收的作业
{
itused++;
}
}//while
if( itused==usedtable.end())
{
cout<<"未找到要回收的作业,请确定所输入的作业名是否正确!"<<endl;
}
}