-
Notifications
You must be signed in to change notification settings - Fork 1
/
ant.c
103 lines (86 loc) · 2 KB
/
ant.c
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
////////////////
//Definitions for an Ant
//
//Ant - walks through the system building a solution
//Adds pheremone for each item selected on its solution
//
#include <stdlib.h>
#include <stdio.h>
#include "ant.h"
#include "item.h"
void ant_init(struct Ant* ant)
{
Knapsack_init(&ant->solution);
}
void ant_fin(struct Ant *ant)
{
//destructor
Knapsack_destroy(&ant->solution);
}
void ant_buildSolution(struct Ant* ant)
{
while(true)
{
struct Neighbour *n = createNeighbour(&ant->solution);
if(n->size == 0){
deleteNeighbour(n);
break;
}
ItemId itemid = Neighbour_randSelect(n);
Knapsack_addItem(&ant->solution, itemid);
deleteNeighbour(n);
}
}
inline Pher ant_getPherDelta(struct Ant* ant)
{
return (Pher)(ant->solution.worth * 0.025);
}
/**
* adds DeltaPher to the delta matrix, which shall be a pointer
* to Pher with exactly NUM_ITEMS elements.
*
* In the first call to this function within a thread, delta shall be
* pre allocated and zero-initalized.
*
* This function is THREAD UNSAFE, and delta shall not
* be shared accross multiple threads.
*/
void ant_getDeltaPherMatrix(struct Ant *ant, Pher *(delta[]))
{
Pher deltaPher = ant_getPherDelta(ant);
for(ItemId i = 0; i < NUM_ITEMS; i++)
{
if(ant->solution.has_item[i])
{
(*delta)[i] += deltaPher;
}
}
}
/**
* Updates item pheromones with a matrix
*/
void ant_updPheromonesMatrix(Pher *(delta[]))
{
for(ItemId i = 0; i < NUM_ITEMS; i++)
{
if( (*delta)[i] != 0)
{
Item_addPheromone(&universe[i], (*delta)[i]);
}
}
}
/**
* Updates pheromones based off current solution
* trails are updated by Q*value
*/
void ant_updatePheromones(struct Ant* ant)
{
Pher delta = ant_getPherDelta(ant);
for(ItemId i = 0; i < NUM_ITEMS; i++)
{
if(ant->solution.has_item[i])
{
Item_addPheromone(&universe[i], delta);
}
}
}