]> git.itanic.dy.fi Git - sudoku/blob - sudoku.cpp
Store the guesses variable as per object instead of global variable
[sudoku] / sudoku.cpp
1 #include <iostream>
2 #include <string>
3
4 #include "sudoku.h"
5 #include "debug.h"
6
7 #define EMPTY ' '
8
9 int verbose = 1;
10
11 sudoku::sudoku()
12 {
13         int x,y;
14
15         for (y = 0; y < 9; y++)
16                 for (x = 0; x < 9; x++)
17                         table[x][y] = EMPTY;
18
19         recursion_depth = 0;
20         guesses = 0;
21 }
22
23 sudoku::~sudoku()
24 {
25 }
26
27 static int check_validity(const int col, const int row)
28 {
29         if (col < 0 || col >= 9) {
30                 DPRINT << "Invalid column: " << col << std::endl;
31                 return 0;
32         }
33
34         if (row < 0 || row >= 9) {
35                 DPRINT << "Invalid row: " << row << std::endl;
36                 return 0;
37         }
38         return 1;
39 }
40
41 char sudoku::get(const int col, const int row)
42 {
43         if (!check_validity(row, col)) {
44                 DPRINT << "over here\n";
45                 return 0;
46         }
47
48         return table[col][row];
49 }
50
51 int sudoku::set(const int col, const int row, const char val)
52 {
53         std::string str;
54
55         if (!check_validity(col, row)) {
56                 DPRINT << "over here\n";
57                 return -1;
58         }
59
60         if (table[col][row] != EMPTY) {
61                 DPRINT << "Assigning value to a non-empty slot\n";
62                 return -1;
63         }
64
65         str = get_col_contents(col);
66         if (str.find(val, 0) != std::string::npos) {
67                 DPRINT << "Illegal assignment " << col << "." << row << ": "
68                        << val << std::endl;
69                 return -1;
70         }
71
72         str = get_row_contents(row);
73         if (str.find(val, 0) != std::string::npos) {
74                 DPRINT << "Illegal assignment " << col << "." << row << ": "
75                        << val << std::endl;
76                 return -1;
77         }
78
79         str = get_block_contents(col, row);
80         if (str.find(val, 0) != std::string::npos) {
81                 DPRINT << "Illegal assignment " << col << "." << row << ": "
82                        << val << std::endl;
83                 return -1;
84         }
85
86
87         table[col][row] = val;
88
89         return 0;
90 }
91
92 int sudoku::str_to_row(const int row, const std::string &str)
93 {
94         unsigned int i, col = 0;
95         char chr;
96
97         if (row < 0 || row >= 9) {
98                 DPRINT << "Illegal row " << row << std::endl;
99                 return -1;
100         }
101
102         for (i = 0; i < str.length(); i++) {
103                 chr = str.at(i);
104
105                 if ((chr == '?') ||
106                     (chr == '_') ||
107                     (chr == '.')){
108                         col++;
109                         continue;
110                 }
111
112                 /* Ignore non-numbers */
113                 if (chr < '1' || chr > '9')
114                         continue;
115
116                 set(col++, row, chr);
117                 if (col >= 9)
118                         break;
119         }
120         return 0;
121 }
122
123 void sudoku::print(void)
124 {
125         int x,y;
126
127         printf("+-------+------+--------+\n");
128         for (y = 0; y < 9; y++) {
129                 printf("| ");
130                 for (x = 0; x < 9; x++) {
131                         printf("%c ", table[x][y]);
132                         if (!((x  + 1)% 3))
133                                 printf("| ");
134                 }
135                 printf("\n");
136                 if (!((y + 1) % 3))
137                         printf("+-------+-------+-------+\n");
138         }
139 }
140
141 void sudoku::clone_to(sudoku &to)
142 {
143         sudoku clone;
144         int x, y;
145
146         for (x = 0; x < 9; x++)
147                 for (y = 0; y < 9; y++)
148                         to.table[x][y] = table[x][y];
149 }
150
151 std::string sudoku::get_row_contents(int row)
152 {
153         std::string s;
154         int col;
155
156         for (col = 0; col < 9; col++) {
157                 if (table[col][row] != EMPTY)
158                         s += table[col][row];
159         }
160
161         return s;
162 }
163
164 std::string sudoku::get_col_contents(int col)
165 {
166         std::string s;
167         int row;
168
169         for (row = 0; row < 9; row++) {
170                 if (table[col][row] != EMPTY)
171                         s += table[col][row];
172         }
173
174         return s;
175 }
176
177 std::string sudoku::get_block_contents(int col, int row)
178 {
179         std::string s;
180         int x, y;
181         char c;
182
183         if (col < 0 || col >= 9)
184                 DPRINT "Aiee " << col << std::endl;
185         if (row < 0 || row >= 9)
186                 DPRINT "Aiee " << row << std::endl;
187
188         col = (col /= 3) * 3;
189         row = (row /= 3) * 3;
190
191         for (y = 0; y < 3; y++)
192                 for (x = 0; x < 3; x++) {
193                         c = get(x + col, y + row);
194                         if (c != EMPTY)
195                                 s += c;
196                 }
197
198         return s;
199 }
200
201 static std::string exclude_common(std::string s1, std::string s2)
202 {
203         std::string::iterator a, b;
204
205 restart:
206         for (a = s1.begin(); a != s1.end(); a++) {
207                 for (b = s2.begin(); b != s2.end(); b++) {
208                         if (*a == *b) {
209                                 a = s1.erase(a);
210                                 b = s2.erase(b);
211                                 goto restart;
212                         }
213                 }
214         }
215         return s1;
216 }
217
218 std::string sudoku::get_legal_numbers(int col, int row)
219 {
220         char val;
221         std::string a, b, c, ret;
222
223         if (!check_validity(col, row)) {
224                 DPRINT << "over here\n";
225                 return NULL;
226         }
227
228         val = get(col, row);
229         if (val != EMPTY) {
230                 return "0";
231         }
232
233 //      std::cout << "[" << col << "." << row << "] ";
234
235         a = get_col_contents(col);
236 //      std::cout << " col " << a;
237
238         b = get_row_contents(row);
239 //      std::cout << " row " << b;
240
241         c = get_block_contents(col, row);
242 //      std::cout << " block " << c;
243
244         ret = exclude_common("123456789", a);
245         ret = exclude_common(ret, b);
246         ret = exclude_common(ret, c);
247
248 //      std::cout << " legal " << ret << std::endl;
249         return ret;
250 }
251
252 int sudoku::fill_missing()
253 {
254         int x, y, solved = 0;
255         std::string num;
256
257         for (y = 0; y < 9; y++)
258                 for (x = 0; x < 9; x++) {
259                                 num = get_legal_numbers(x, y);
260                                 if ((num != "0") && (num.length() == 1)) {
261                                         set(x, y, num[0]);
262                                         solved++;
263                         }
264                 }
265         if (verbose) {
266                 std::cout << "Solved " << solved << " numbers\n";
267         }
268
269         return solved;
270 }
271
272 int sudoku::get_best_guess(int &col, int &row)
273 {
274         int x, y;
275         int min = 0, filled = 0, illegals = 0;
276         std::string numbers;
277
278         /*
279          * Initialize row and col with illegal values to spot possible
280          * misuse
281          */
282         col = -1;
283         row = -1;
284
285         for (y = 0; (y < 9) && !illegals; y++)
286                 for (x = 0; x < 9; x++) {
287                         numbers = get_legal_numbers(x, y);
288
289                         if (numbers == "0") {
290                                 filled++;
291                                 continue;
292                         }
293
294                         if (numbers.length() == 0) {
295                                 illegals++;
296                                 break;
297                         }
298
299                         if (!min) {
300                                 min = numbers.length();
301                                 col = x;
302                                 row = y;
303                                 continue;
304                         }
305
306                         if ((int)numbers.length() < min) {
307                                 min = numbers.length();
308                                 col = x;
309                                 row = y;
310                                 if (min == 1)
311                                         return min;
312                         }
313 //                      std::cout <<  x << "." << y << ": " << " min " 
314 //                                << numbers << col << "." << row << std::endl;
315                 }
316
317         if ((!min && !filled) || illegals) {
318 //              DPRINT << "Is this sudoku has no solutions?\n";
319                 return -1;
320         }
321
322         if (!min && (filled == 99)) {
323                 DPRINT << "This sudoku is solved\n";
324                 return 0;
325         }
326
327         return min;
328 }
329
330 sudoku sudoku::solve(int &solvable)
331 {
332         int x, y, i, ret;
333         std::string str;
334         sudoku empty;
335
336         // Fill in as much as possible
337         do {
338                 if (verbose) {
339                         std::cout << std::endl;
340                         print();
341                 }
342         } while (fill_missing() != 0);
343
344         ret = get_best_guess(x, y);
345
346         // Did we solve it yet?
347         switch (ret) {
348         case -1:
349                 // Unsolvable
350                 solvable = 0;
351                 if (verbose) {
352                         std::cout << "This is unsolvable, recursion: " 
353                                   << recursion_depth << std::endl;
354                 }
355                 return empty;
356         case 0:
357                 // Solved
358                 solvable = 1;
359                 if (verbose) {
360                         std::cout << "Solution found , recursion: " 
361                                   << recursion_depth << std::endl;
362                 }
363                 return *this;
364         }
365
366         if (verbose) {
367                 std::cout << "Not solved yet, guessing at depth "
368                           << recursion_depth << std::endl;
369         }
370
371         // Try guessim something
372         str = get_legal_numbers(x, y);
373         for (i = 0; i < (int)str.length(); i++) {
374
375                 sudoku guess = *this;
376                 guess.set(x, y, str[i]);
377
378                 if (verbose) {
379                         std::cout << "Guessing number " << str[i] << " to "
380                                   << x << "." << y << std::endl;
381                 }
382                 
383                 guess.recursion_depth = recursion_depth + 1;
384
385                 int can_solve;
386                 guess = guess.solve(can_solve);
387                 
388                 //Did it solve?
389                 if (can_solve)
390                         return guess;
391         }
392
393         // It didn't solve
394         solvable = 0;
395         return empty;
396 }
397
398 std::vector<sudoku> sudoku::solve_all()
399 {
400         int x, y, i, j, ret;
401         std::string str;
402         std::vector<sudoku> sudokus;
403
404         // Fill in as much as possible
405         do {
406                 if (verbose) {
407                         std::cout << std::endl;
408                         print();
409                 }
410         } while (fill_missing() != 0);
411
412         ret = get_best_guess(x, y);
413
414         // Did we solve it yet?
415         switch (ret) {
416         case -1:
417                 // Unsolvable
418                 if (verbose) {
419                         std::cout << "This is unsolvable, recursion: " 
420                                   << recursion_depth << std::endl;
421                 }
422                 return sudokus;
423         case 0:
424                 // Solved
425                 if (verbose) {
426                         std::cout << "Solution found , recursion: " 
427                                   << recursion_depth << std::endl;
428                 }
429                 sudokus.push_back(*this);
430                 print();
431                 return sudokus;
432         }
433
434         if (verbose) {
435                 std::cout << "Not solved yet, guessing at depth "
436                           << recursion_depth << std::endl;
437         }
438
439         // Try guessim something
440         str = get_legal_numbers(x, y);
441         for (i = 0; i < (int)str.length(); i++) {
442                 std::vector<sudoku> results;
443
444                 sudoku guess = *this;
445                 guesses++;
446
447                 if (verbose) {
448                         std::cout << "Guessing number " << str[i] << " to "
449                                   << x << "." << y << std::endl;
450                 }
451
452                 guess.set(x, y, str[i]);
453                 guess.recursion_depth = recursion_depth + 1;
454                 guess.guesses = 0;
455
456                 results = guess.solve_all();
457                 guesses += guess.guesses;
458                 
459                 //Did it solve?
460                 if (!results.empty()) {
461 /*                      printf("Got %d solutions, guessed %d: %s\n",
462                                (int)results.size(), (int)str.size(),
463                                str.c_str());*/
464
465                         for(j = 0;j < (int)results.size(); j++) {
466                                 sudokus.push_back(results.at(j));
467                                 guesses += results.at(j).guesses;
468                         }
469                 }
470         }
471
472         std::cout << "Guesses: " << guesses << std::endl;
473
474         // Return what was solved
475         return sudokus;
476 }
477