//文件geneset.h
#pragma once
#include "routgene.h"
class GeneSet
{
public:
GeneSet(int _nodeNum,int **&_netArray,int **&_valArray);
~GeneSet(void);
void AddRear(RoutGene &gene);
RoutGene & First(void);
void RemoveFirst(void);
void Sort(void);
RoutGene & GetBest(void);
void RemoveHalf(void);
int REAR(void);
void RemoveAll(void);
private:
RoutGene geneArray[MAX_GENE_NUMBER];
int rear;
int nodeNum;
int **&netArray;
int **&valArray;
private:
//计算gene中路由的长度
int Distance(RoutGene & gene);
//计算从ii到jj路由长度最小的gene
int MinGene(int ii, int jj);
};
//文件geneset.cpp
#include "geneset.h"
#using <mscorlib.dll>
#include "resource.h"
using namespace GeneResource;
GeneSet::GeneSet(int _nodeNum,int **&_netArray,int **&_valArray)
:netArray(_netArray),valArray(_valArray)
{
nodeNum = _nodeNum;
for(int i=0;i<MAX_GENE_NUMBER;i++)
geneArray[i].SetNodeNum(nodeNum);
rear = 0;
}
GeneSet::~GeneSet(void)
{
}
void GeneSet::AddRear(RoutGene &gene)
{
if(rear<MAX_GENE_NUMBER)
{
geneArray[rear] = gene;
rear ++;
}
}
RoutGene & GeneSet::First(void)
{
//TODO: return statement
return geneArray[0];
}
void GeneSet::RemoveFirst(void)
{
for(int i=0;i<rear-1;i++)
geneArray[i] = geneArray[i+1];
if(rear>=1)
{
geneArray[rear-1].SetNodeNum(nodeNum);
rear --;
}
}
void GeneSet::Sort(void)
{//对gene进行排序
RoutGene gene = geneArray[0];
int MIN = 0;
for(int i=0;i<rear;i++)
{
MIN = MinGene(i,rear-1);
if(i!=MIN)
{
gene = geneArray[i];
geneArray[i] = geneArray[MIN];
geneArray[MIN] = gene;
}
}
}
RoutGene & GeneSet::GetBest(void)
{//调用需在Sort之后
//TODO: return statement
return geneArray[0];
}
void GeneSet::RemoveHalf(void)
{
if( rear/2 > 0)
{
for(int i=rear/2;i<rear;i++)
geneArray[i].SetNodeNum(nodeNum);
rear = rear/2;
}
}
void GeneSet::RemoveAll(void)
{
while(rear>0)
{
geneArray[rear-1].SetNodeNum(nodeNum);
-- rear;
}
}
int GeneSet::REAR(void)
{
return rear;
}
int GeneSet::Distance(RoutGene & gene)
{//计算gene中路由的长度
NodeSet nodeSet = NODE(gene);
int max = nodeSet.GetLastIndex();
int distance = 0,row = 0,col = 0;
for(int i=0;i<max;i++)
{
row = *(nodeSet.GetpNodeSet()+i);
col = *(nodeSet.GetpNodeSet()+i+1);
distance += valArray[row][col];
}
return distance;
}
int GeneSet::MinGene(int ii, int jj)
{
//rear>jj>=ii>=0
RoutGene gene = geneArray[ii];
int result = ii;
for(int i=ii;i<=jj;i++)
{
if(Distance(gene)>Distance(geneArray[i]))
{
gene = geneArray[i];
result = i;
}
}
return result;
}