Debian Codegraph @

main.cpp

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /*
2 * qqwing - Sudoku solver and generator
3 * Copyright (C) 2006-2014 Stephen Ostermiller http://ostermiller.org/
4 * Copyright (C) 2007 Jacques Bensimon ([email protected])
5 * Copyright (C) 2011 Jean Guillerez (j.guillerez - orange.fr)
6 * Copyright (C) 2014 Michael Catanzaro ([email protected])
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22 #include "config.h"
23
24 #include <cstdio>
25 #include <cstdlib>
26 #include <cstring>
27 #include <iostream>
28
29 #if HAVE_GETTIMEOFDAY == 1
30 #include <sys/time.h>
31 #else
32 #include <time.h>
33 #endif
34
35 #include "qqwing.hpp"
36
37 using namespace qqwing;
38 using namespace std;
39
40 long getMicroseconds();
41 bool readPuzzleFromStdIn(int* puzzle);
42 void printHelp();
43 void printVersion();
44 void printAbout();
45
46 /**
47 * Main method -- the entry point into the program.
48 * Run with --help as an argument for usage and documentation
49 */
50 int main(int argc, char *argv[]){
51 try {
52 // Start time for the application for timing
53 long applicationStartTime = getMicroseconds();
54
55 // The number of puzzles solved or generated.
56 int puzzleCount = 0;
57
58 enum Action {NONE, GENERATE, SOLVE};
59
60 // defaults for options
61 bool printPuzzle = false;
62 bool printSolution = false;
63 bool printHistory = false;
64 bool printInstructions = false;
65 bool timer = false;
66 bool countSolutions = false;
67 Action action = NONE;
68 bool logHistory = false;
69 SudokuBoard::PrintStyle printStyle = SudokuBoard::READABLE;
70 int numberToGenerate = 1;
71 bool printStats = false;
72 SudokuBoard::Difficulty difficulty = SudokuBoard::UNKNOWN;
73 SudokuBoard::Symmetry symmetry = SudokuBoard::NONE;
74
75 // Read the arguments and set the options
76 {for (int i=1; i<argc; i++){
77 if (!strcmp(argv[i],"--puzzle")){
78 printPuzzle = true;
79 } else if (!strcmp(argv[i],"--nopuzzle")){
80 printPuzzle = false;
81 } else if (!strcmp(argv[i],"--solution")){
82 printSolution = true;
83 } else if (!strcmp(argv[i],"--nosolution")){
84 printSolution = false;
85 } else if (!strcmp(argv[i],"--history")){
86 printHistory = true;
87 } else if (!strcmp(argv[i],"--nohistory")){
88 printHistory = false;
89 } else if (!strcmp(argv[i],"--instructions")){
90 printInstructions = true;
91 } else if (!strcmp(argv[i],"--noinstructions")){
92 printInstructions = false;
93 } else if (!strcmp(argv[i],"--stats")){
94 printStats = true;
95 } else if (!strcmp(argv[i],"--nostats")){
96 printStats = false;
97 #if HAVE_GETTIMEOFDAY == 1
98 } else if (!strcmp(argv[i],"--timer")){
99 timer = true;
100 } else if (!strcmp(argv[i],"--notimer")){
101 timer = false;
102 #endif
103 } else if (!strcmp(argv[i],"--count-solutions")){
104 countSolutions = true;
105 } else if (!strcmp(argv[i],"--nocount-solutions")){
106 countSolutions = false;
107 } else if (!strcmp(argv[i],"--generate")){
108 action = GENERATE;
109 printPuzzle = true;
110 if (i+1 < argc && argv[i+1][0] != '-'){
111 numberToGenerate = atoi(argv[i+1]);
112 if (numberToGenerate <= 0){
113 cout << "Bad number of puzzles to generate: " << argv[i+1] << endl;
114 return 1;
115 }
116 i++;
117 }
118 } else if (!strcmp(argv[i],"--difficulty")){
119 if (argc <= i+1){
120 cout << "Please specify a difficulty." << endl;
121 return 1;
122 } else if (!strcmp(argv[i+1],"simple")){
123 difficulty = SudokuBoard::SIMPLE;
124 } else if (!strcmp(argv[i+1],"easy")){
125 difficulty = SudokuBoard::EASY;
126 } else if (!strcmp(argv[i+1],"intermediate")){
127 difficulty = SudokuBoard::INTERMEDIATE;
128 } else if (!strcmp(argv[i+1],"expert")){
129 difficulty = SudokuBoard::EXPERT;
130 } else if (!strcmp(argv[i+1],"any")){
131 difficulty = SudokuBoard::UNKNOWN;
132 } else {
133 cout << "Difficulty expected to be simple, easy, intermediate, expert, or any, not " << argv[i+1] << endl;
134 return 1;
135 }
136 i++;
137 } else if (!strcmp(argv[i],"--symmetry")){
138 if (argc <= i+1){
139 cout << "Please specify a symmetry." << endl;
140 return 1;
141 } else if (!strcmp(argv[i+1],"none")){
142 symmetry = SudokuBoard::NONE;
143 } else if (!strcmp(argv[i+1],"rotate90")){
144 symmetry = SudokuBoard::ROTATE90;
145 } else if (!strcmp(argv[i+1],"rotate180")){
146 symmetry = SudokuBoard::ROTATE180;
147 } else if (!strcmp(argv[i+1],"mirror")){
148 symmetry = SudokuBoard::MIRROR;
149 } else if (!strcmp(argv[i+1],"flip")){
150 symmetry = SudokuBoard::FLIP;
151 } else if (!strcmp(argv[i+1],"random")){
152 symmetry = SudokuBoard::RANDOM;
153 } else {
154 cout << "Symmetry expected to be none, rotate90, rotate180, mirror, flip, or random, not " << argv[i+1] << endl;
155 return 1;
156 }
157 i++;
158 } else if (!strcmp(argv[i],"--solve")){
159 action = SOLVE;
160 printSolution = true;
161 } else if (!strcmp(argv[i],"--log-history")){
162 logHistory = true;
163 } else if (!strcmp(argv[i],"--nolog-history")){
164 logHistory = false;
165 } else if (!strcmp(argv[i],"--one-line")){
166 printStyle=SudokuBoard::ONE_LINE;
167 } else if (!strcmp(argv[i],"--compact")){
168 printStyle=SudokuBoard::COMPACT;
169 } else if (!strcmp(argv[i],"--readable")){
170 printStyle=SudokuBoard::READABLE;
171 } else if (!strcmp(argv[i],"--csv")){
172 printStyle=SudokuBoard::CSV;
173 } else if (!strcmp(argv[i],"-n") || !strcmp(argv[i],"--number")){
174 if (i+1 < argc){
175 numberToGenerate = atoi(argv[i+1]);
176 i++;
177 } else {
178 cout << "Please specify a number." << endl;
179 return 1;
180 }
181 } else if (!strcmp(argv[i],"-h") || !strcmp(argv[i],"--help") || !strcmp(argv[i],"help") || !strcmp(argv[i],"?")){
182 printHelp();
183 return 0;
184 } else if (!strcmp(argv[i],"--version")){
185 printVersion();
186 return 0;
187 } else if (!strcmp(argv[i],"--about")){
188 printAbout();
189 return 0;
190 } else {
191 cout << "Unknown argument: '" << argv[i] << "'" << endl;
192 printHelp();
193 return 1;
194 }
195 }}
196
197 if (action == NONE){
198 cout << "Either --solve or --generate must be specified." << endl;
199 printHelp();
200 return 1;
201 }
202
203 // Initialize the random number generator
204 srand ( unsigned ( time(0) ) );
205
206 // If printing out CSV, print a header
207 if (printStyle == SudokuBoard::CSV){
208 if (printPuzzle) cout << "Puzzle,";
209 if (printSolution) cout << "Solution,";
210 if (printHistory) cout << "Solve History,";
211 if (printInstructions) cout << "Solve Instructions,";
212 if (countSolutions) cout << "Solution Count,";
213 if (timer) cout << "Time (milliseconds),";
214 if (printStats) cout << "Givens,Singles,Hidden Singles,Naked Pairs,Hidden Pairs,Pointing Pairs/Triples,Box/Line Intersections,Guesses,Backtracks,Difficulty";
215 cout << "" << endl;
216 }
217
218 // Create a new puzzle board
219 // and set the options
220 SudokuBoard* ss = new SudokuBoard();
221 ss->setRecordHistory(printHistory || printInstructions || printStats || difficulty!=SudokuBoard::UNKNOWN);
222 ss->setLogHistory(logHistory);
223 ss->setPrintStyle(printStyle);
224
225 // Solve puzzle or generate puzzles
226 // until end of input for solving, or
227 // until we have generated the specified number.
228 bool done = false;
229 int numberGenerated = 0;
230 while (!done){
231 // record the start time for the timer.
232 long puzzleStartTime = getMicroseconds();
233
234 // iff something has been printed for this particular puzzle
235 bool printedSomething = false;
236
237 // Record whether the puzzle was possible or not,
238 // so that we don't try to solve impossible givens.
239 bool havePuzzle = false;
240 if (action == GENERATE){
241 // Generate a puzzle
242 havePuzzle = ss->generatePuzzleSymmetry(symmetry);
243 if (!havePuzzle && printPuzzle){
244 cout << "Could not generate puzzle.";
245 if (printStyle==SudokuBoard::CSV){
246 cout << ",";
247 } else {
248 cout << endl;
249 }
250 printedSomething = true;
251 }
252 } else {
253 // Read the next puzzle on STDIN
254 int* puzzle = new int[BOARD_SIZE];
255 if (readPuzzleFromStdIn(puzzle)){
256 havePuzzle = ss->setPuzzle(puzzle);
257 if (!havePuzzle){
258 if (printPuzzle){
259 ss->printPuzzle();
260 printedSomething = true;
261 }
262 if (printSolution) {
263 cout << "Puzzle is not possible.";
264 if (printStyle==SudokuBoard::CSV){
265 cout << ",";
266 } else {
267 cout << endl;
268 }
269 printedSomething = true;
270 }
271 }
272 } else {
273 // Set loop to terminate when nothing is left on STDIN
274 havePuzzle = false;
275 done = true;
276 }
277 delete[] puzzle;
278 }
279
280 int solutions = 0;
281
282 if (havePuzzle){
283
284 // Count the solutions if requested.
285 // (Must be done before solving, as it would
286 // mess up the stats.)
287 if (countSolutions){
288 solutions = ss->countSolutions();
289 }
290
291 // Solve the puzzle
292 if (printSolution || printHistory || printStats || printInstructions || difficulty!=SudokuBoard::UNKNOWN){
293 ss->solve();
294 }
295
296 // Bail out if it didn't meet the difficulty standards for generation
297 if (action == GENERATE){
298 if (difficulty!=SudokuBoard::UNKNOWN && difficulty!=ss->getDifficulty()){
299 havePuzzle = false;
300 } else {
301 numberGenerated++;
302 // Set loop to terminate if enough have been generated.
303 if (numberGenerated >= numberToGenerate) done = true;
304 }
305 }
306 }
307
308 // Check havePuzzle again, it may have changed based on difficulty
309 if (havePuzzle){
310
311 // With a puzzle now in hand and possibly solved
312 // print out the solution, stats, etc.
313 printedSomething = true;
314
315 // Record the end time for the timer.
316 long puzzleDoneTime = getMicroseconds();
317
318 // Print the puzzle itself.
319 if (printPuzzle) ss->printPuzzle();
320
321 // Print the solution if there is one
322 if (printSolution){
323 if (ss->isSolved()){
324 ss->printSolution();
325 } else {
326 cout << "Puzzle has no solution.";
327 if (printStyle==SudokuBoard::CSV){
328 cout << ",";
329 } else {
330 cout << endl;
331 }
332 }
333 }
334
335 // Print the steps taken to solve or attempt to solve the puzzle.
336 if (printHistory) ss->printSolveHistory();
337 // Print the instructions for solving the puzzle
338 if (printInstructions) ss->printSolveInstructions();
339
340 // Print the number of solutions to the puzzle.
341 if (countSolutions){
342 if (printStyle == SudokuBoard::CSV){
343 cout << solutions << ",";
344 } else {
345 if (solutions == 0){
346 cout << "There are no solutions to the puzzle." << endl;
347 } else if (solutions == 1){
348 cout << "The solution to the puzzle is unique." << endl;
349 } else {
350 cout << "There are " << solutions << " solutions to the puzzle." << endl;
351 }
352 }
353 }
354
355 // Print out the time it took to solve the puzzle.
356 if (timer){
357 double t = ((double)(puzzleDoneTime - puzzleStartTime))/1000.0;
358 if (printStyle == SudokuBoard::CSV){
359 cout << t << ",";
360 } else {
361 cout << "Time: " << t << " milliseconds" << endl;
362 }
363 }
364
365 // Print any stats we were able to gather while solving the puzzle.
366 if (printStats){
367 int givenCount = ss->getGivenCount();
368 int singleCount = ss->getSingleCount();
369 int hiddenSingleCount = ss->getHiddenSingleCount();
370 int nakedPairCount = ss->getNakedPairCount();
371 int hiddenPairCount = ss->getHiddenPairCount();
372 int pointingPairTripleCount = ss->getPointingPairTripleCount();
373 int boxReductionCount = ss->getBoxLineReductionCount();
374 int guessCount = ss->getGuessCount();
375 int backtrackCount = ss->getBacktrackCount();
376 string difficultyString = ss->getDifficultyAsString();
377 if (printStyle == SudokuBoard::CSV){
378 cout << givenCount << "," << singleCount << "," << hiddenSingleCount
379 << "," << nakedPairCount << "," << hiddenPairCount
380 << "," << pointingPairTripleCount << "," << boxReductionCount
381 << "," << guessCount << "," << backtrackCount
382 << "," << difficultyString << ",";
383 } else {
384 cout << "Number of Givens: " << givenCount << endl;
385 cout << "Number of Singles: " << singleCount << endl;
386 cout << "Number of Hidden Singles: " << hiddenSingleCount << endl;
387 cout << "Number of Naked Pairs: " << nakedPairCount << endl;
388 cout << "Number of Hidden Pairs: " << hiddenPairCount << endl;
389 cout << "Number of Pointing Pairs/Triples: " << pointingPairTripleCount << endl;
390 cout << "Number of Box/Line Intersections: " << boxReductionCount << endl;
391 cout << "Number of Guesses: " << guessCount << endl;
392 cout << "Number of Backtracks: " << backtrackCount << endl;
393 cout << "Difficulty: " << difficultyString << endl;
394 }
395 }
396 puzzleCount++;
397 }
398 if (printedSomething && printStyle == SudokuBoard::CSV){
399 cout << endl;
400 }
401 }
402
403 delete ss;
404
405 long applicationDoneTime = getMicroseconds();
406 // Print out the time it took to do everything
407 if (timer){
408 double t = ((double)(applicationDoneTime - applicationStartTime))/1000000.0;
409 cout << puzzleCount << " puzzle" << ((puzzleCount==1)?"":"s") << " " << (action==GENERATE?"generated":"solved") << " in " << t << " seconds." << endl;
410 }
411
412
413 } catch (char const* s){
414 cout << s << endl;
415 return 1;
416 }
417
418 return 0;
419 }
420
421 void printVersion(){
422 cout << PACKAGE_STRING << endl;
423 }
424
425 void printAbout(){
426 cout << "qqwing - Sudoku solver and generator" << endl;
427 cout << "Copyright (C) 2006-2014 Stephen Ostermiller http://ostermiller.org/" << endl;
428 cout << "Copyright (C) 2007 Jacques Bensimon ([email protected])" << endl;
429 cout << "Copyright (C) 2011 Jean Guillerez (j.guillerez - orange.fr)" << endl;
430 cout << "Copyright (C) 2014 Michael Catanzaro ([email protected])" << endl;
431 cout << "" << endl;
432 cout << "This program is free software; you can redistribute it and/or modify" << endl;
433 cout << "it under the terms of the GNU General Public License as published by" << endl;
434 cout << "the Free Software Foundation; either version 2 of the License, or" << endl;
435 cout << "(at your option) any later version." << endl;
436 cout << "" << endl;
437 cout << "This program is distributed in the hope that it will be useful," << endl;
438 cout << "but WITHOUT ANY WARRANTY; without even the implied warranty of" << endl;
439 cout << "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the" << endl;
440 cout << "GNU General Public License for more details." << endl;
441 cout << "" << endl;
442 cout << "You should have received a copy of the GNU General Public License along" << endl;
443 cout << "with this program; if not, write to the Free Software Foundation, Inc.," << endl;
444 cout << "51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA." << endl;
445 }
446
447 void printHelp(){
448 cout << "qqwing <options>" << endl;
449 cout << "Sudoku solver and generator." << endl;
450 cout << " --generate <num> Generate new puzzles" << endl;
451 cout << " --solve Solve all the puzzles from standard input" << endl;
452 cout << " --difficulty <diff> Generate only simple, easy, intermediate, expert, or any" << endl;
453 cout << " --symmetry <sym> Symmetry: none, rotate90, rotate180, mirror, flip, or random" << endl;
454 cout << " --puzzle Print the puzzle (default when generating)" << endl;
455 cout << " --nopuzzle Do not print the puzzle (default when solving)" << endl;
456 cout << " --solution Print the solution (default when solving)" << endl;
457 cout << " --nosolution Do not print the solution (default when generating)" << endl;
458 cout << " --stats Print statistics about moves used to solve the puzzle" << endl;
459 cout << " --nostats Do not print statistics (default)" << endl;
460 #if HAVE_GETTIMEOFDAY == 1
461 cout << " --timer Print time to generate or solve each puzzle" << endl;
462 cout << " --notimer Do not print solve or generation times (default)" << endl;
463 #endif
464 cout << " --count-solutions Count the number of solutions to puzzles" << endl;
465 cout << " --nocount-solutions Do not count the number of solutions (default)" << endl;
466 cout << " --history Print trial and error used when solving" << endl;
467 cout << " --nohistory Do not print trial and error to solve (default)" << endl;
468 cout << " --instructions Print the steps (at least 81) needed to solve the puzzle" << endl;
469 cout << " --noinstructions Do not print steps to solve (default)" << endl;
470 cout << " --log-history Print trial and error to solve as it happens" << endl;
471 cout << " --nolog-history Do not print trial and error to solve as it happens" << endl;
472 cout << " --one-line Print puzzles on one line of 81 characters" << endl;
473 cout << " --compact Print puzzles on 9 lines of 9 characters" << endl;
474 cout << " --readable Print puzzles in human readable form (default)" << endl;
475 cout << " --csv Output CSV format with one line puzzles" << endl;
476 cout << " --help Print this message" << endl;
477 cout << " --about Author and license information" << endl;
478 cout << " --version Display current version number" << endl;
479 }
480
481 /**
482 * Read a sudoku puzzle from standard input.
483 * STDIN is processed one character at a time
484 * until the sudoku is filled in. Any digit
485 * or period is used to fill the sudoku, any
486 * other character is ignored.
487 */
488 bool readPuzzleFromStdIn(int* puzzle){
489 int read = 0;
490 while (read < BOARD_SIZE){
•491 int c = getchar();
492 if (c == EOF) return false;
493 if (c >= '1' && c <='9'){
494 puzzle[read] = c-'0';
495 read++;
496 }
497 if (c == '.' || c == '0'){
498 puzzle[read] = 0;
499 read++;
500 }
501 }
502 return true;
503 }
504
505 /**
506 * Get the current time in microseconds.
507 */
508 long getMicroseconds(){
509 #if HAVE_GETTIMEOFDAY == 1
510 struct timeval tv;
511 gettimeofday(&tv, NULL);
512 return tv.tv_sec*1000000+tv.tv_usec;
513 #else
514 return 0;
515 #endif
516 }