蚁群算法初步尝试
#include
using namespace std;
static int road[3][3];
static int pheromone[3][3];
void printLine();
int Random(int start, int end); // 随机数函数
class Ant
{ // 蚂蚁
public:
int distance = 0;
int roadChoose[3] = {-1, -1, -1};
void run(int i);
};
void showRoad();
void showPheromone();
void printResult();
void Initialize();
void InitializeAnt(Ant &ant);
void record(Ant ant);
int main()
{
srand((unsigned)time(NULL));
Initialize();
showRoad();
Ant antArr[3];
char control = 'Y';
while (control == 'Y')
{
for (int i = 0; i < 3; i++)
{
InitializeAnt(antArr[i]);
}
for (int i = 0; i < 3; i++)
{
printLine();
for (int j = 0; j < 3; j++)
{
antArr[j].run(i);
cout << antArr[j].distance << " ";
}
cout << endl;
}
int minDistance = antArr[0].distance;
for (int i = 0; i < 3; i++)
{
if (minDistance > antArr[i].distance)
{
minDistance = antArr[i].distance;
}
}
printLine();
for (int i = 0; i < 3; i++)
{
if (antArr[i].distance == minDistance)
{
cout << "mindistance is : " << minDistance << endl;
record(antArr[i]);
}
}
showPheromone();
printLine();
cout << "Continue ? (Y/N):" << endl;
cin >> control;
}
printResult();
}
void printLine()
{
cout << "--------------------------------" << endl;
}
int Random(int start, int end) // 随机数函数
{
int dis = end - start;
return rand() % dis + start;
}
void showRoad()
{ // 打印路程距离
cout << "--------------------------------" << endl;
cout << "Road Distance Information :" << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << road[i][j] << " ";
}
cout << endl;
}
};
void showPheromone()
{
printLine();
cout << "Pheromone :" << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << pheromone[i][j] << " ";
}
cout << endl;
}
}
void printResult()
{
printLine();
printLine();
cout << "Result :" << endl;
showRoad();
printLine();
cout << "the shortest road might be :" << endl;
for (int i = 0; i < 3; i++)
{
int max = pheromone[i][0];
for (int j = 0; j < 3; j++)
{
if (max < pheromone[i][j])
{
max = pheromone[i][j];
}
}
for (int j = 0; j < 3; j++)
{
if (max == pheromone[i][j])
{
if (i == 0)
{
cout << "(" << i + 1 << ", " << j + 1 << ")";
}
else
{
cout << " -> "
<< "(" << i + 1 << ", " << j + 1 << ")";
}
}
}
}
}
void Initialize()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
road[i][j] = Random(1, 16);
}
}
}
void InitializeAnt(Ant &ant)
{
ant.distance = 0;
}
void record(Ant ant)
{
int a = ant.roadChoose[0], b = ant.roadChoose[1], c = ant.roadChoose[2];
cout << "recorded :" << endl
<< "[0][" << a << "]" << endl
<< "[1][" << b << "]" << endl
<< "[2][" << c << "]" << endl;
pheromone[0][a] += 1;
pheromone[1][b] += 1;
pheromone[2][c] += 1;
}
void Ant::run(int i){
{ // 随机走路
this->roadChoose[i] = Random(0, 3);
this->distance += road[i][roadChoose[i]];
}
}