-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
354 lines (304 loc) · 11.3 KB
/
main.cpp
File metadata and controls
354 lines (304 loc) · 11.3 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
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
#include <algorithm>
#include <random>
#include <cmath>
#include <iostream>
#include <vector>
#include <set>
#include <chrono>
#include <thread> //only for pauses between different tests
using namespace std;
inline bool isDecimalCharacter(char c) {
return (c >= '0') && (c <= '9');
}
void fillBoardArray(const vector<vector<char>>& out, vector<vector<int>>& board, vector<vector<bool>>& fixed_squares) {
for (int i = 0; i < 9; i++) {
board[i].resize(9);
fixed_squares[i].resize(9);
for (int j = 0; j < 9; j++) {
if (isDecimalCharacter(out[i][j])) {
board[i][j] = out[i][j] - '0';
fixed_squares[i][j] = true;
} else {
board[i][j] = 0;
fixed_squares[i][j] = false;
}
}
}
}
void initializeBoard(vector<vector<int>>& board, const vector<vector<bool>>& fixed_squares, mt19937& generator) {
// For each 3x3 block, fill with missing numbers
for (int blockRow = 0; blockRow < 3; blockRow++) {
for (int blockCol = 0; blockCol < 3; blockCol++) {
// Track used numbers in this block
set<int> usedNumbers;
vector<pair<int, int>> emptyCells;
// First pass: collect used numbers and empty cells
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int r = blockRow * 3 + i;
int c = blockCol * 3 + j;
if (board[r][c] != 0) {
usedNumbers.insert(board[r][c]);
} else if (!fixed_squares[r][c]) {
emptyCells.push_back({r, c});
}
}
}
// Determine missing numbers
vector<int> missingNumbers;
for (int num = 1; num <= 9; num++) {
if (usedNumbers.find(num) == usedNumbers.end()) {
missingNumbers.push_back(num);
}
}
// Shuffle and assign to empty cells
shuffle(missingNumbers.begin(), missingNumbers.end(), generator);
for (size_t idx = 0; idx < emptyCells.size(); idx++) {
int r = emptyCells[idx].first;
int c = emptyCells[idx].second;
board[r][c] = missingNumbers[idx];
}
}
}
}
int cost(const vector<vector<int>>& board) {
int totalCost = 0;
// Check rows
for (int i = 0; i < 9; i++) {
vector<int> count(10, 0);
for (int j = 0; j < 9; j++) {
count[board[i][j]]++;
}
for (int num = 1; num <= 9; num++) {
if (count[num] > 1) totalCost += count[num] - 1;
}
}
// Check columns
for (int j = 0; j < 9; j++) {
vector<int> count(10, 0);
for (int i = 0; i < 9; i++) {
count[board[i][j]]++;
}
for (int num = 1; num <= 9; num++) {
if (count[num] > 1) totalCost += count[num] - 1;
}
}
// Check 3x3 blocks
for (int blockRow = 0; blockRow < 3; blockRow++) {
for (int blockCol = 0; blockCol < 3; blockCol++) {
vector<int> count(10, 0);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int r = blockRow * 3 + i;
int c = blockCol * 3 + j;
count[board[r][c]]++;
}
}
for (int num = 1; num <= 9; num++) {
if (count[num] > 1) totalCost += count[num] - 1;
}
}
}
return totalCost;
}
void generateNeighbor(vector<vector<int>>& board, const vector<vector<bool>>& fixed_squares, mt19937& generator) {
// Select a random 3x3 block
int blockRow = uniform_int_distribution<int>(0, 2)(generator);
int blockCol = uniform_int_distribution<int>(0, 2)(generator);
// Find mutable cells in this block
vector<pair<int, int>> mutableCells;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int r = blockRow * 3 + i;
int c = blockCol * 3 + j;
if (!fixed_squares[r][c]) {
mutableCells.push_back({r, c});
}
}
}
if (mutableCells.size() < 2) return;
// Select two distinct cells to swap
uniform_int_distribution<int> dist(0, mutableCells.size() - 1);
int idx1 = dist(generator);
int idx2 = dist(generator);
while (idx1 == idx2) {
idx2 = dist(generator);
}
// Swap the values
swap(board[mutableCells[idx1].first][mutableCells[idx1].second],
board[mutableCells[idx2].first][mutableCells[idx2].second]);
}
void generateDiversificationMove(vector<vector<int>>& board, const vector<vector<bool>>& fixed_squares, mt19937& generator) {
// With a small probability, make a more significant change
// Reinitialize a random block to escape local minima
int blockRow = uniform_int_distribution<int>(0, 2)(generator);
int blockCol = uniform_int_distribution<int>(0, 2)(generator);
// Collect fixed numbers in this block
set<int> fixedNumbers;
vector<pair<int, int>> mutableCells;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int r = blockRow * 3 + i;
int c = blockCol * 3 + j;
if (fixed_squares[r][c]) {
fixedNumbers.insert(board[r][c]);
} else {
mutableCells.push_back({r, c});
}
}
}
// Determine available numbers
vector<int> availableNumbers;
for (int num = 1; num <= 9; num++) {
if (fixedNumbers.find(num) == fixedNumbers.end()) {
availableNumbers.push_back(num);
}
}
// Shuffle and assign to mutable cells
shuffle(availableNumbers.begin(), availableNumbers.end(), generator);
for (size_t i = 0; i < mutableCells.size(); i++) {
int r = mutableCells[i].first;
int c = mutableCells[i].second;
board[r][c] = availableNumbers[i];
}
}
void PrintCurrentBoardAndCost(const vector<vector<int>>& board, int cost, long iterations) {
cout << "Iteration: " << iterations << ", Cost: " << cost << endl;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
void solveSudoku(vector<vector<char>>& out) {
vector<vector<int>> board(9);
vector<vector<bool>> fixed_squares(9);
fillBoardArray(out, board, fixed_squares);
std::random_device rand_dev;
std::mt19937 generator(rand_dev());
std::uniform_real_distribution<> realDistribution(0, 1);
// Initialize board with valid blocks
initializeBoard(board, fixed_squares, generator);
int currentCost = cost(board);
double temperature = 20.0;
double coolingRate = 0.99995;
double minTemperature = 0.0001;
long iterations = 0;
int sameCostCount = 0;
int lastCost = currentCost;
auto startTime = chrono::steady_clock::now();
while (temperature > minTemperature && currentCost > 0) {
vector<vector<int>> newBoard = board;
// With a small probability, make a diversification move
if (realDistribution(generator) < 0.05) {
generateDiversificationMove(newBoard, fixed_squares, generator);
} else {
generateNeighbor(newBoard, fixed_squares, generator);
}
int newCost = cost(newBoard);
int costDiff = newCost - currentCost;
if (costDiff <= 0) {
board = newBoard;
currentCost = newCost;
} else {
double probability = exp(-costDiff / temperature);
if (realDistribution(generator) < probability) {
board = newBoard;
currentCost = newCost;
}
}
temperature *= coolingRate;
iterations++;
// Check for stagnation
if (currentCost == lastCost) {
sameCostCount++;
if (sameCostCount > 5000) {
// Randomize to escape local minimum
initializeBoard(board, fixed_squares, generator);
currentCost = cost(board);
temperature = 20.0;
sameCostCount = 0;
}
} else {
sameCostCount = 0;
lastCost = currentCost;
}
// Print progress occasionally
if (iterations % 10000 == 0) {
PrintCurrentBoardAndCost(board, currentCost, iterations);
// Check if we're taking too long
auto currentTime = chrono::steady_clock::now();
auto elapsed = chrono::duration_cast<chrono::seconds>(currentTime - startTime).count();
if (elapsed > 30) { // 30 seconds timeout
cout << "Timeout reached. Restarting with new initialization." << endl;
initializeBoard(board, fixed_squares, generator);
currentCost = cost(board);
temperature = 20.0;
startTime = chrono::steady_clock::now();
}
}
// If cost is zero, we found a solution
if (currentCost == 0) {
break;
}
}
// Output the solution
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (!fixed_squares[i][j]) {
out[i][j] = '0' + board[i][j];
}
}
}
}
int main() {
vector<vector<char>> test = {
{'5','3','.','.','7','.','.','.','.'},
{'6','.','.','1','9','5','.','.','.'},
{'.','9','8','.','.','.','.','6','.'},
{'8','.','.','.','6','.','.','.','3'},
{'4','.','.','8','.','3','.','.','1'},
{'7','.','.','.','2','.','.','.','6'},
{'.','6','.','.','.','.','2','8','.'},
{'.','.','.','4','1','9','.','.','5'},
{'.','.','.','.','8','.','.','7','9'}
};
vector<vector<char>> test2 = {
{'.','2','6','5','.','.','.','9','.'},
{'5','.','.','.','7','9','.','.','4'},
{'3','.','.','.','1','.','.','.','.'},
{'6','.','.','.','.','.','8','.','7'},
{'.','7','5','.','2','.','.','1','.'},
{'.','1','.','.','.','.','4','.','.'},
{'.','.','.','3','.','8','9','.','2'},
{'7','.','.','.','6','.','.','4','.'},
{'.','3','.','2','.','.','1','.','.'}
};
vector<vector<vector<char>>> tests = {test, test2};
int testCounter = 0;
for(vector<vector<char>> test : tests){
solveSudoku(test);
cout << "Final Solution:" << endl;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
cout << test[i][j] << " ";
}
cout << endl;
}
// Verify the solution
vector<vector<int>> board(9);
vector<vector<bool>> fixed_squares(9);
fillBoardArray(test2, board, fixed_squares);
int finalCost = cost(board);
cout << "Final cost: " << finalCost << endl;
testCounter++;
if(testCounter >= tests.size()) return 0;
std::cout << "Waiting 5 seconds before the next test" << std::endl;
std::chrono::seconds sleepDuration(5);
std::this_thread::sleep_for( sleepDuration );
std::cout << "Waited 5s\n";
}
return 0;
}