-
Notifications
You must be signed in to change notification settings - Fork 0
/
algorithm.cpp
767 lines (609 loc) · 18.9 KB
/
algorithm.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
#include "algorithm.h"
// ZMIENNE
list <int> *q;
list <int> *sq;
bool *visited,found=false;
int value=0,shortest_path=0;
vector <int> current_path;
vector <int> next_path;;
uniform_real_distribution<float> random_float_0_1(0.0, 1.0);
mt19937 engine (time(NULL)); // Mersenne twister MT19937 silnik
/// BRUTE FORCE ALGORITHMS ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///// ///// ///// /////
void brute_force()
{
visited = new bool[n];
q = new list<int>;
sq = new list<int>;
for(int i=0;i<n;i++) visited[i]=false;
hamilton_B(0);
cout<<"Najkrotsza sciezka to: "<<shortest_path<<endl<<"Cykl: ";
for(list<int>::iterator it = sq->begin();it!=sq->end();it++)
{
cout<<*it<<" ";
}
delete visited;
delete q;
delete sq;
shortest_path = 0;
value = 0;
getchar();
getchar();
}
void hamilton_B(int v)
{
q->push_back(v);
if( (q->size())==n )
{
value+=graph[0][v];
if( (value<shortest_path) || (shortest_path==0) )
{
shortest_path = value;
sq->assign(q->begin(), q->end());
}
value-=graph[0][v];
}
else
{
visited[v]= true;
for(int i=0;i<n;i++)
{
if( visited[i] == false )
{
value+=graph[v][i];
hamilton_B(i);
value-=graph[v][i];
}
}
visited[v] = false;
}
q->pop_back();
}
/// GREEDY ALGORITHMS ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///// ///// ///// /////
void greedy()
{
visited = new bool[n];
q = new list<int>;
sq = new list<int>;
for(int i=0;i<n;i++) visited[i]=false;
for(int i=0;i<n;i++) hamilton_G(i);
cout<<"Najkrotsza sciezka to: "<<shortest_path<<endl<<"Cykl: ";
for(list<int>::iterator it = sq->begin();it!=sq->end();it++)
{
cout<<*it<<" ";
}
delete visited;
delete q;
delete sq;
shortest_path = 0;
value = 0;
found=false;
getchar();
getchar();
}
int hamilton_G(int v)
{
q->push_back(v);
if( (q->size())==n )
{
for(list<Edge>::iterator it = Graph[v].begin(); it != Graph[v].end(); it++)
if((it->v)==0)
{
value+=it->w;
if( (value<shortest_path) || (shortest_path == 0) )
{
shortest_path = value;
sq->assign(q->begin(), q->end());
}
value=0;
found = true;
return 0;
}
}
else
{
visited[v]= true;
for(list<Edge>::iterator it = Graph[v].begin(); it != Graph[v].end(); it++)
{
if( visited[it->v] == false )
{
value+=it->w;
hamilton_G(it->v);
if(found) return 0;
value-=it->w;
}
}
visited[v] = false;
}
q->pop_back();
}
/// ANT COLONY ALGORITHMS ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///// ///// ///// /////
void ant_colony()
{
srand(time(NULL));
const int loop_number = 1000;
int** ants = CreateAnts();
int *best_path = ShortestPath(ants);
double bestLength = CycleLength(best_path);
double **pheromones = InitializePheromones();
int counter = 0;
while (counter < loop_number)
{
UpdateAnts(ants, pheromones);
UpdatePheromones(pheromones, ants);
int *currBestTrail = ShortestPath(ants);
double currBestLength = CycleLength(currBestTrail);
if (currBestLength < bestLength)
{
delete best_path;
best_path = NULL;
bestLength = currBestLength;
best_path = currBestTrail;
}
counter++;
}
cout<<bestLength;
getchar();
getchar();
}
int **CreateAnts()
{
int **ants = new int *[ANT_NUMBER];
int random;
for(int i=0;i<ANT_NUMBER;i++)
{
random = rand() % n;
ants[i] = CreateRandomPath(random);
}
return ants;
}
int *CreateRandomPath(const int start)
{
vector <int> trail; // wektor opisuj�cy losow� �cie�k�
for(int i=0;i<n;i++) trail.push_back(i); // wrzucenie do wektora �cie�ki od 0 do n-1
random_shuffle(trail.begin(),trail.end()); // wymieszanie losowe warto�ci wektora (�cie�ki)
int temp = FindIndexOf(start,&trail[0]); // Szuka indeks w kt�rym znajduje si� warto�� 'start'
swap(trail[0],trail[temp]);
int *tab = new int[n];
for(int i=0;i<n;i++)
tab[i] = trail[i];
return tab; // zwraca adres pocz�tkowy wektora i przypisuje do jakiej� tablicy int
}
double **InitializePheromones()
{
double **pheromones = new double*[n];
for (int i=0; i<n; i++)
pheromones[i] = new double[n];
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
pheromones[i][j] = 1.0; // tablica dwuwymiarowa ca�a zape�niana warto�ciami 0.01
return pheromones;
}
void UpdateAnts(int **ants, double **pheromones)
{
for (int i = 0; i < ANT_NUMBER; i++)
{
int start = rand() % n;
ants[i] = BuildNewPath(i, start, pheromones);
}
}
int *BuildNewPath(int k, int start, double **pheromones)
{
int *trail = new int[n];
bool *visited = new bool[n];
trail[0] = start;
visited[start] = true;
for (int i = 0; i < n-1; ++i)
{
int city = trail[i];
int next = ChooseNextCity(k, city, visited, pheromones);
trail[i+1] = next;
visited[next] = true;
}
return trail;
}
int ChooseNextCity(int k, int city, bool *visited, double **pheromones)
{
double *probabilites = FindProbabilites(k, city, visited, pheromones);
double *cumul = new double[n + 1];
cumul[0] = 0.0;
for (int i = 0; i < n; ++i)
cumul[i + 1] = cumul[i] + probabilites[i];
random_device rd;
default_random_engine e( rd() ); // seed PRNG
uniform_real_distribution <> liczba( 0.0, 1.0 ); // przedzial liczb
double p = liczba( e );
for (int i = 0; i < n ; i++)
if (p >= cumul[i] && p < cumul[i + 1])
return i;
}
int *ShortestPath(int **ants)
{
double bestLength = CycleLength(ants[0]);
int idxBestLength = 0;
for (int k = 1; k < ANT_NUMBER ; ++k)
{
double len = CycleLength(ants[k]);
if (len < bestLength)
{
bestLength = len;
idxBestLength = k;
}
}
int *bestPath = new int[n];
for(int i=0; i<n; i++)
bestPath[i] = ants[idxBestLength][i];
return bestPath;
}
double CycleLength(int *ants)
{
double value=0;
for(int i=0;i<n-1;i++)
value+=EdgeLength(ants[i],ants[i+1]);
value+=EdgeLength(ants[0],ants[n-1]);
return value;
}
double *FindProbabilites(int k, const int city, bool *visited, double **pheromones)
{
double *taueta = new double[n];
double sum = 0.0;
for (int i = 0; i < n; ++i)
{
if (i == city)
taueta[i] = 0.0; // Prawdopodobie�stwo przej�cia z miasta x do miasta x wynosi 0
else if (visited[i] == true)
taueta[i] = 0.0; // Prawdopodobie�stwo przej�cia z miasta x do miasta odwiedzonego wynosi 0
else
{
taueta[i] = pow(pheromones[city][i], ALPHA) * pow((1.0 / EdgeLength(city, i)), BETA); // obliczenie prawdopodobie�stwa wed�ug okre�lonego wzoru
if (taueta[i] < 0.0001)
taueta[i] = 0.0001;
else if (taueta[i] > (MaxValue() / (n * 100)))
taueta[i] = MaxValue() / (n * 100);
}
sum += taueta[i];
}
double *probs = new double[n];
for (int i = 0; i <n; ++i)
probs[i] = taueta[i] / sum;
return probs;
}
void UpdatePheromones(double **pheromones, int **ants)
{
int rho = RHO;
int q = Q;
for (int i = 0; i < n ; ++i)
{
for (int j = i + 1; j < n; ++j)
{
for (int k = 0; k < ANT_NUMBER; ++k)
{
double length = CycleLength(ants[k]);
double decrease = (1.0 - rho) * pheromones[i][j];
double increase = 0.0;
if (IsEdgeInTrail(i, j, ants[k]) == true) increase = (q / length);
pheromones[i][j] = decrease + increase;
if (pheromones[i][j] < 0.0001)
pheromones[i][j] = 0.0001;
else if (pheromones[i][j] > 100000.0)
pheromones[i][j] = 100000.0;
pheromones[j][i] = pheromones[i][j];
}
}
}
}
bool IsEdgeInTrail(int cityX, int cityY, int *path)
{
int lastIndex = n - 1;
int idx = FindIndexOf(cityX, path);
if (idx == 0 && path[1] == cityY) return true;
else if (idx == 0 && path[lastIndex] == cityY) return true;
else if (idx == 0) return false;
else if (idx == lastIndex && path[lastIndex - 1] == cityY) return true;
else if (idx == lastIndex && path[0] == cityY) return true;
else if (idx == lastIndex) return false;
else if (path[idx - 1] == cityY) return true;
else if (path[idx + 1] == cityY) return true;
else return false;
}
int EdgeLength(const int a, const int b)
{
return graph[a][b];
}
int FindIndexOf(const int idx,int *tab)
{
for(int i=0;i<n;i++)
if(idx==tab[i])
return i;
}
double MaxValue()
{
return numeric_limits<double>::max( );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// 2-Opt //przyrost czasu przy liczbie wierzcholkow z zakresu 70-75 /// ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void opt2()
{
int *path = new int[n];
for(int i=0; i<n; i++)
{
path[i]=i;
}
random_shuffle(path,path+n);
int b1, c1, e1, f1, nr = 0, temp;
do
{
flaga:
b1 = path[nr];
c1 = path[nr+1];
for (int g=nr+2; g<n-1; g++)
{
e1 = path[g];
f1 = path[g+1];
if ( (graph[b1][c1]+graph[e1][f1]) > (graph[b1][e1]+graph[c1][f1]) )
{
temp = path[nr+1];
path[nr+1] = path[g];
path[g] = temp;
goto flaga;
}
}
nr++;
}
while (nr<n-2);
//clock tutaj;
int waga=0;
for(int i=n-2; i>-1; i--)
{
waga+=graph[path[i]][path[i+1]];
}
cout<<endl<<endl<<"Najkrotsza sciezka to: "<<waga<<endl;
cout<<"Cykl po optymalizacji: ";
for(int i=0; i<n; i++)
{
cout<<path[i]<<" ";
}
delete path;
cout<<endl<<endl;
system("pause");
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// 3-Opt //u mnie powyżej 13 wierzcholkow duze czasy ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void opt3()
{
int *path3 = new int[n];
for(int i=0; i<n; i++)
{
path3[i]=i;
}
random_shuffle(path3,path3+n);
int a3, b3, c3, d3, e3, f3, nr3 = 0, temp3, min3;
int fixed[7];
int switcher;
do
{
flaga3:
a3 = path3[nr3];
b3 = path3[nr3+1];
for (int g=nr3+2; g<n-3; g++)
{
c3 = path3[g];
d3 = path3[g+1];
for (int h=g+2; h<n-1; h++)
{
switcher = 7;
e3 = path3[h];
f3 = path3[h+1];
min3 = graph[a3][b3] + graph[c3][d3] + graph[e3][f3];
fixed[0]=graph[a3][d3] + graph[e3][b3] + graph[c3][f3];
fixed[1]=graph[a3][c3] + graph[b3][e3] + graph[d3][f3];
fixed[2]=graph[a3][d3] + graph[e3][c3] + graph[b3][f3];
fixed[3]=graph[a3][e3] + graph[d3][b3] + graph[c3][f3];
//
fixed[4]=graph[a3][e3] + graph[d3][c3] + graph[b3][f3];
fixed[5]=graph[a3][b3] + graph[c3][e3] + graph[d3][f3];
fixed[6]=graph[a3][c3] + graph[b3][d3] + graph[e3][f3];
for (int i=0; i<7; i++)
{
if (fixed[i] < min3 )
{
min3 = fixed[i];
switcher = i;
}
}
switch(switcher)
{
case 0:
swap(path3[nr3+1],path3[g+1]);
swap(path3[g],path3[h]);
goto flaga3;
case 1:
swap(path3[nr3+1],path3[g]);
swap(path3[g+1],path3[h]);
goto flaga3;
case 2:
temp3=path3[nr3+1];
path3[nr3+1]=path3[g+1];
path3[g+1]=path3[g];
path3[g]=path3[h];
path3[h]=temp3;
goto flaga3;
case 3:
temp3=path3[nr3+1];
path3[nr3+1]=path3[h];
path3[h]=path3[g];
path3[g]=path3[g+1];
path3[g+1]=temp3;
goto flaga3;
case 4:
swap(path3[nr3+1],path3[h]);
swap(path3[g],path3[g+1]);
goto flaga3;
case 5:
swap(path3[g+1],path3[h]);
goto flaga3;
case 6:
swap(path3[nr3+1],path3[g]);
goto flaga3;
case 7:
break;
}
}
}
nr3++;
}
while (nr3<n-4);
int waga3=0;
for(int i=n-2; i>-1; i--)
{
waga3+=graph[path3[i]][path3[i+1]];
}
cout<<endl<<endl<<"Najkrotsza sciezka to: "<<waga3<<endl;
cout<<"Cykl po optymalizacji: ";
for(int i=0; i<n; i++)
{
cout<<path3[i]<<" ";
}
delete path3;
cout<<endl<<endl;
system("pause");
}
double GetTotalDistance(vector<int> order){
double distance = 0;
for (int i = 0; i < (int)order.size() - 1; i++){
distance += graph[order[i]][order[i + 1]];
}
if (order.size() > 0){
distance += graph[order[order.size() - 1]][order[0]];
}
return distance;
}
vector <int> GetNextArrangement(vector<int> order){
vector <int> newOrder = *new vector<int>();
for (int i = 0; i < (int)order.size(); i++)
newOrder.push_back(order[i]);
//we will only rearrange two cities by random
//starting point should be always zero - so zero should not be included
int firstRandomCityIndex = rand() % newOrder.size();
int secondRandomCityIndex = rand() % newOrder.size();
int temp = newOrder[firstRandomCityIndex];
newOrder[firstRandomCityIndex] = newOrder[secondRandomCityIndex];
newOrder[secondRandomCityIndex] = temp;
return newOrder;
}
void get_first_path(){
current_path.clear();
for(int i=0; i<n; i++){
current_path.push_back(i);
}
std::random_shuffle(current_path.begin(), current_path.end());
current_path.push_back(current_path[0]);
}
void Annealing() {
int iteration = -1;
double temperature = 10000.0;
double deltaDistance = 0;
double coolingRate = 0.9999;
double absoluteTemperature = 0.00001;
auto rand_float = std::bind(random_float_0_1, engine);
get_first_path(); //<- wybieramy losowa sciezke od ktorej zaczynamy
double distance = GetTotalDistance(current_path); //<- suma wag obecnej sciezki
while (temperature > absoluteTemperature)
{
next_path = GetNextArrangement(current_path); // <- wybierz nowa sciezke i wstaw jako nastepna
deltaDistance = GetTotalDistance(next_path) - distance; //<- roznica w dlugosci miedzy pierwsza a druga sciezka
//jesli nowa sciezka jest krotsza niz stara
//lub jesli nowa sciezka jest dluzsza lecz spelnia warunek Boltzmana P = exp(fd/T)
if ((deltaDistance < 0) || (distance > 0 && exp(-deltaDistance / temperature) > rand_float())) //exp() ; rand_float -> zwracanie losowej z zakresu 0.0;1.0
{
for (int i = 0; i < (int)next_path.size(); i++) //<- next_q->size zwraca ilosc elementow na liscie nextorder
current_path[i] = next_path[i]; //<- czyli jesli spelniony jest warunek z ifa, to uznajemy ze nextorder jest lepszy i przypisujemy jako aktualny
distance = deltaDistance + distance; //<- po prostu sumujemy distance z przyrostem distance (moze byc ujemny, wtedy sciezka optymalniejsza)
}
//znizamy temperature
temperature *= coolingRate;
iteration++;
}
shortest_path = distance; //<- na samym koncu przypisujemy distance jako najkrotsza sciezke zwrocona
printf("shortest_path = %d", shortest_path);
getchar();
getchar();
}
////////TABU SEARCH
void tabuMove(int city1, int city2, vector<vector<int> > tabuList){ //tabus the swap operation
tabuList[city1][city2]+= 5;
tabuList[city2][city1]+= 5;
}
void decrementTabu(vector<vector<int> > tabuList){
for(int i = 0; i<(int)tabuList.size(); i++){
for(int j = 0; j<(int)tabuList.size(); j++){
tabuList[i][j]-=tabuList[i][j]<=0?0:1;
}
}
}
//swaps two cities
vector <int> swapOperator(int city1, int city2, vector <int> solution) {
int temp = solution[city1];
solution[city1] = solution[city2];
solution[city2] = temp;
return solution;
}
std::vector<int> getBestNeighbour(vector<vector<int> > tabuList, vector <int> initSolution) {
vector <int> bestSol((int)initSolution.size());
bestSol = initSolution;
int bestCost = GetTotalDistance(initSolution);
int city1 = 0;
int city2 = 0;
bool firstNeighbor = true;
for (int i = 1; i < (int)bestSol.size() - 1; i++) {
for (int j = 2; j < (int)bestSol.size() - 1; j++) {
if (i == j) {
continue;
}
vector <int> newBestSol(bestSol.size());
newBestSol = bestSol;
newBestSol = swapOperator(i, j, initSolution); //sproboj zamienic miasta
int newBestCost = GetTotalDistance(newBestSol);
if ((newBestCost > bestCost || firstNeighbor) && tabuList[i][j] == 0) { //jesli znaleziono lepszy ruch - zapisz
firstNeighbor = false;
city1 = i;
city2 = j;
bestSol = newBestSol;
bestCost = newBestCost;
}
}
}
if (city1 != 0) {
decrementTabu(tabuList);
tabuMove(city1, city2, tabuList);
}
return bestSol;
}
void TabuSearch(){
int debug;
int number_of_iterations = 100;
int TabuLength = n;
get_first_path();
vector<vector<int> > tabuList(TabuLength, std::vector<int>(TabuLength));
vector <int> bestSol((int)current_path.size());
bestSol = current_path;
int shortest_path = GetTotalDistance(current_path);
for (int i = 0; i < number_of_iterations;i++) {
current_path = getBestNeighbour(tabuList, current_path);
int currCost = GetTotalDistance(current_path);
if (currCost < shortest_path) {
bestSol = current_path;
shortest_path = currCost;
}
}
printf("shortest_path = %d", shortest_path);
getchar();
getchar();
}