-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
131 lines (106 loc) · 1.91 KB
/
Copy pathmain.cpp
File metadata and controls
131 lines (106 loc) · 1.91 KB
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
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <stdio.h>
#define n 8
typedef struct gameState
{
int gameState[n];
}state;
state createInitialState();
int utility(state s);
double temperature(double time);
state generateNextRandom(state currentState);
state simulatedAnnealing(state initialState);
int main()
{
srand(time(NULL));
state initialState;
for (int count = 0; count < 100; count++)
{
initialState = createInitialState();
initialState = simulatedAnnealing(initialState);
if (utility(initialState) == 0)
{
for (int i = 0; i < n; i++)
{
printf("%d ", initialState.gameState[i]);
}
printf("\n");
}
else
{
printf("FAILURE\n");
}
}
return 0;
}
state createInitialState()
{
state s;
for (int i = 0; i < n; i++)
{
s.gameState[i] = rand() % 7 + 1;
}
return s;
}
state simulatedAnnealing(state initialState)
{
int deltaUtil = 0;
double time = 1;
double Temperature = temperature(time);
state current = initialState;
state next;
while (Temperature > 0)
{
next = generateNextRandom(current);
deltaUtil = utility(current) - utility(next);
if (deltaUtil > 0)
{
current = next;
}
else
{
if (rand() % (int)(100 / exp(deltaUtil / Temperature)) == 1)
current = next;
}
time++;
Temperature = temperature(time);
}
return current;
}
double temperature(double time)
{
time = 200 - time * 0.001;
return time;
}
state generateNextRandom(state currentState)
{
int column = rand() % n;
int pos = rand() % n + 1;
currentState.gameState[column] = pos;
return currentState;
}
int utility (state s)
{
int utility = 0;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (s.gameState[i] == s.gameState[j])
{
utility++;
}
else if (s.gameState[i] == s.gameState[j] + i - j)
{
utility++;
}
else if (s.gameState[i] == s.gameState[j] - i + j)
{
utility++;
}
}
}
return utility;
}