def test_sudoku_set_square(self): ''' Same as test_sudoku_set_row but for squares ''' sudoku = Sudoku() for k, num in product(range(0, 9), range(1, 10)): sudoku.squares[k] = num self.assertTrue(np.all(sudoku.squares[k].flatten() == num)) for k in range(0, 9): sudoku.squares[k] = np.arange(1, 10).reshape(3, 3) self.assertTrue( np.all(sudoku.squares[k].flatten() == np.arange(1, 10))) for y, x in product(range(0, 3), range(0, 3)): sudoku.squares[y, x] = np.random.randint(9, size=9).reshape([3, 3 ]) + 1 self.assertTrue( np.all(sudoku.squares[y, x].flatten() == sudoku.squares[ y * 3 + x].flatten())) for k in range(0, 9): square = sudoku.squares[k] for y, x in product(range(0, 3), range(0, 3)): self.assertRaises(Exception, square.__setitem__, (y, x), -1)
def test_get_valid_qudrant(): s = Sudoku(sConstants.unsolved_sudoku) expected = [i for i in range(1, 10)] for i in range(sConstants.quadrant_size): for j in range(sConstants.quadrant_size): quadrant = s.get_quadrant_as_list(i, j) assert quadrant == expected
def _check_intersect(s, h1, h2): # When two houses intersect, # some numbers cannot at the same time be outside of the intersection # Thus they must be inside the intersection changed = 0 log.append("In House {0} & {1}:", h1, h2) h1u = util.difference(h1, h2) # h1 unique tiles h2u = util.difference(h2, h1) # h2 unique tiles h1un = s.get_numbers(h1u) # h1 unique numbers h2un = s.get_numbers(h2u) # h2 unique numbers h1i = Sudoku.other(h1un) # h1 intersect-only numbers h2i = Sudoku.other(h2un) # h2 intersect-only numbers hi = util.union(h1i, h2i) # intersect-only numbers if len(hi) > 0: @log.rollback def rem(): log.indent() log.append("Intersection contains {0}", hi) log.indent() result = max(section_remove(s, h2u, h1i), section_remove(s, h1u, h2i)) log.dedent(2) return result changed = rem() return changed
def main(): InputFile = open('sudoku.txt') game_board = list() for line in InputFile: game_board += [int(i) for i in line.split(' ')] # Close the text file InputFile.close # Create the sudoku object board = Sudoku(game_board) if AC3(board): isSolved = True for tile in board.variables: if len(board.domain[tile]) > 1: isSolved = False if(isSolved): print("Solution Found") # print(board.domain) print("|", end = "" ) count = 0 row = 0 for x in board.domain: if count == 9: count = 0 print() # starts new line row += 1 if row == 3 or row == 6: print() print('|', end='') if count == 3 or count == 6: print(" |", end="") print("{}|".format(board.domain[x][0]), end="") count += 1 else: assigned = define_assigned_vars(board) assignments = backtrack(assigned, board) for domain in board.domain: board.domain[domain] = assignments[domain] if len(domain) > 1 else board.domain[domain] print("Solution Found") # print(board.domain) print("|", end = "" ) count = 0 row = 0 for x in board.domain: if count == 9: count = 0 print() # starts new line row += 1 if row == 3 or row == 6: print() print('|', end='') if count == 3 or count == 6: print(" |", end="") print("{}|".format(board.domain[x]), end="") count += 1
def setUp(self): self.game = Sudoku([ "53xx7xxxx", "6xx195xxx", "x98xxxx6x", "8xxx6xxx3", "4xx8x3xx1", "7xxx2xxx6", "x6xxxx28x", "xxx419xx5", "xxxx8xx79" ], 9) self.game4 = Sudoku(["x2xx", "x3x2", "x124", "2xx1"], 4)
def __init__(self, puzzle_file): ''' Initialize the solver instance. The lower the number of the puzzle file the easier it is. It is a good idea to start with the easy puzzles and verify that your solution is correct manually. You should run on the hard puzzles to make sure you aren't violating corner cases that come up. Harder puzzles will take longer to solve. :param puzzle_file: the puzzle file to solve ''' self.sudoku = Sudoku( puzzle_file) # this line has to be here to initialize the puzzle # print ("Sudoku", Sudoku.board_str(self.sudoku)) # print("board", self.sudoku.board) - List of Lists self.num_guesses = 0 # self.unassigned = deque() self.assignment = {} # make domian the Given Puzzle self.domains = deepcopy(self.sudoku.board) # Overwrite 0's with their possiblilities. for row in range(0, 9): for col in range(0, 9): # extract value value = self.sudoku.board[row][col] if value == 0: self.domains[row][col] = [1, 2, 3, 4, 5, 6, 7, 8, 9] # add this index to unassigned for faster look ups # self.unassigned.append((row,col)) else: self.domains[row][col] = value self.assignment[(row, col)] = value vars = []
def test_game_over_2(self): self.game = Sudoku([ "533175384", "612195537", "298376369", "882668363", "481863981", "71732x356", "169836281", "916419925", "816288179" ], 9) self.assertEqual(self.game.juego_terminado(), False)
def backtracking_hard(runs): print("*********************************************\n" "Deterministic Algorithms on backtracking_hard\n" "*********************************************") puzzle = "backtracking_hard.txt" with open('results.txt', 'a') as results_file: results_file.write( "\n\n\n" + str(runs) + " runs for each deterministic solver on backtracking_hard puzzle\n\n" ) results_file.flush() print("~puzzle:", puzzle, flush=True) results_file.write("\n~~~ " + puzzle + " ~~~\n") results_file.flush() for solver in solvers: print(" -", solver) sum_time = 0 actions = 0 for i in range(runs): game = Sudoku(filename="puzzles/" + puzzle, display_enabled=False, print=False, solver_type=solver) time, actions, is_solved = game.play() sum_time += time results_file.write(" " + solver + " time: " + str(round(sum_time / runs, 3)) + " actions:" + str(actions) + "\n") results_file.flush()
def test_get_invalid_quadrant(): s = Sudoku(sConstants.unsolved_sudoku) try: quadrant = s.get_quadrant_as_list(sConstants.quadrant_size, sConstants.quadrant_size) except IndexError: pass
def __init__(self, size=3): Gtk.Window.__init__(self, title="Sudoku Example") self.size = size # This is an instance of a Sudoku solver self.sudoku = Sudoku(size) # Draw the window self.table = [[Gtk.Entry() for _ in xrange(size**2)] for _ in xrange(size**2)] vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.add(vbox) grid = Gtk.Grid() vbox.add(grid) for row, lst in enumerate(self.table): for col, entry in enumerate(lst): entry.set_max_length(3) entry.set_hexpand(True) entry.set_vexpand(True) entry.set_width_chars(2) grid.attach(entry, col, row, 1, 1) self.solve_button = Gtk.Button(label="Solve") self.solve_button.set_hexpand(True) vbox.add(self.solve_button) self.solve_button.connect("clicked", self.solve) self.clear_button = Gtk.Button(label="Clear") self.clear_button.set_hexpand(True) vbox.add(self.clear_button) self.clear_button.connect("clicked", self.clear)
def csp_sdk(folder, instance): fo = open("problems/%d/%d.sd"%(folder,instance), "rw+") sys.setrecursionlimit(1000000) sudoku = Sudoku() for line in fo: l = line.split() tmp = [] for i in l: tmp.append(int(i)) if l: sudoku.add_row(tmp) fo.close() starter = sudoku.rst_cst_var() csp = Solver(sudoku, starter) result = csp.game() for l in result.sudoku: print l del sudoku print("\n") return csp.steps
def test_recursive_solve(): rec_sudoku = " , , , , 5, 3, , , ;\n" + \ "1, , , 6, , , , , 8;\n" + \ " , 5, , , , 1, , 4, ;\n" + \ "4, , , , 9, , 5, 3, ;\n" + \ " , , 9, 7, , 6, 8, , ;\n" + \ " , 2, 7, , 3, , , , 6;\n" + \ " , 4, , 1, , , , 8, ;\n" + \ "2, , , , , 7, , , 1;\n" + \ " , , , 3, 2, , , , ;\n" solution = "6, 8, 4, 2, 5, 3, 1, 7, 9;\n" + \ "1, 9, 3, 6, 7, 4, 2, 5, 8;\n" + \ "7, 5, 2, 9, 8, 1, 6, 4, 3;\n" + \ "4, 1, 6, 8, 9, 2, 5, 3, 7;\n" + \ "5, 3, 9, 7, 1, 6, 8, 2, 4;\n" + \ "8, 2, 7, 4, 3, 5, 9, 1, 6;\n" + \ "3, 4, 5, 1, 6, 9, 7, 8, 2;\n" + \ "2, 6, 8, 5, 4, 7, 3, 9, 1;\n" + \ "9, 7, 1, 3, 2, 8, 4, 6, 5;\n" sudoku = Sudoku() sudoku.read_string(rec_sudoku) sudoku.recursive_solve() assert_equal(str(sudoku), solution)
def test_possibilities_when_incomplete(): s = Sudoku() # Remove '1', '2' and the top-left block from a completed Sudoku. s.set( dedent("""\ ------------- |000|456|789| |000|789|003| |000|003|456| ------------- |034|567|890| |567|890|034| |890|034|567| ------------- |345|678|900| |678|900|345| |900|345|678| ------------- """)) assert s.possible_entries(0, 0) == [1, 2] assert s.possible_entries(0, 1) == [1, 2] assert s.possible_entries(0, 2) == [1, 2, 3] assert s.possible_entries(1, 0) == [1, 2, 4] assert s.possible_entries(1, 1) == [1, 2, 5] assert s.possible_entries(1, 2) == [1, 2, 6] assert s.possible_entries(2, 0) == [1, 2, 7] assert s.possible_entries(2, 1) == [1, 2, 8] assert s.possible_entries(2, 2) == [1, 2, 9]
def onPbjugarClicked(self): """Despliega la ventana con el tablero para empezar el juego *Crea una instancia de la clase Sudoku y la muestra. *Verificara que se halla escogido un solo nivel de dificultad. *Verificara que halla escogido al menos una opcion de alerta.""" facil=self.ui.rBFacil.isChecked() medio=self.ui.rBMedio.isChecked() dificil=self.ui.rBDificil.isChecked() experto=self.ui.rBExperto.isChecked() invalida=self.ui.cbInvalidas.isChecked() incorrecta=self.ui.cbIncorrectas.isChecked() ayuda=self.ui.cbhelp.isChecked() if facil==False and medio==False and dificil==False and experto==False: self.MessageBox(None,"Seleccione Un Nivel De Dificultad..!","ERROR",self.MB_ICONERROR) elif invalida==False and incorrecta==False: self.MessageBox(None,"Seleccione al menos una opcion de alertas..!","ERROR",self.MB_ICONERROR) elif facil: self.n= Sudoku(1,invalida,incorrecta,ayuda,"") self.n.setVisible(True) self.close() elif medio: self.n= Sudoku(2,invalida,incorrecta,ayuda,"") self.n.setVisible(True) self.close() elif dificil: self.n= Sudoku(3,invalida,incorrecta,ayuda,"") self.n.setVisible(True) self.close() elif experto: self.n= Sudoku(4,invalida,incorrecta,ayuda,"") self.n.setVisible(True) self.close()
def __init__(self, root): self.sudoku = Sudoku() self.root = root self.mainframe = tk.Frame(self.root) self.draw_sudoku() self.draw_buttons() self.mainframe.pack(expand=True)
def main(): with open('sudokus_3x3.txt', 'r') as myfile: content = myfile.readlines() # for each sudoku content = [content[0]] # for testing solved = 0 for i in range(len(content)): line = content[i].strip() sudoku = Sudoku(line) sudoku.solve() if sudoku.is_solved: if ''.join(sudoku.sudoku) == borcic.sudoku99(line): solved += 1 else: print 'My solution:', ''.join(sudoku.sudoku) print 'Expected: ', borcic.sudoku99(line) raise RuntimeError('Got wrong solution!') else: print 'Couldnt finish Sudoku:\n', sudoku.to_string(), '\n' print 'Candidates are:\n', '\n'.join(['\t|'.join(line) for line in sudoku.candidates]) print 'Solving sudoku', i, ':', sudoku.is_solved print 'Solved', solved, 'from a total of', len(content), 'sudokus (' + str(round((solved*100.0)/len(content), 2)) + '%)'
def solve( grid, index, total ): # Função para resolver o sudoku proposto, com a implementação do algoritmo de AC-3 inicio = time.time() sudoku = Sudoku(grid) print("\n Sudoku \n") print("{}".format(sudoku.__str1__(grid))) print("\nAC3 iniciou") AC3_result = AC3(sudoku) if not AC3_result: print("\nEste Sudoku não tem solução") else: if sudoku.terminou(): print( "\n\033[32mAC3 é suficiente para resolver o Sudoku!\033[0;0m") print("\nSolução: \n\n{}".format(sudoku.__str2__())) for cel in sudoku.celulas: val = sudoku.possibilidades[cel] value.append(val[0]) fim = time.time() timeExec = round((fim - inicio), 3) print("Tempo de Execução: " + str(timeExec) + " s") return str(timeExec) else: print("\033[33mEste Sudoku não tem resultado com o AC3\033[0;0m")
def deterministic_algorithms_on_paper_puzzles(runs): print("*******************************************\n" "Deterministic algorithms on regular puzzles\n" "*******************************************") with open('results.txt', 'a') as results_file: paper_puzzles = [ "easy.txt", "medium.txt", "hard.txt", "backtracking_hard.txt" ] results_file.write( str(runs) + " runs for each deterministic solver on each puzzle\n\n") results_file.flush() for puzzle in paper_puzzles: print("~puzzle:", puzzle, flush=True) results_file.write("\n~~~ " + puzzle + " ~~~\n") results_file.flush() for solver in solvers: print(" -", solver) sum_time = 0 actions = 0 for i in range(runs): game = Sudoku(filename="puzzles/" + puzzle, display_enabled=False, print=False, solver_type=solver) time, actions, is_solved = game.play() sum_time += time results_file.write(" " + solver + " time: " + str(round(sum_time / runs, 3)) + " actions:" + str(actions) + "\n") results_file.flush()
def main(): input_csv_file_name = "sudokus_start.txt" output_csv_file_name = "output.txt" puzzles = Reader.read(input_csv_file_name) Reporter.write_output( file_name = output_csv_file_name, content = "", should_overwrite_file = True ) for puzzle in puzzles: solver = "AC3" results = Sudoku.solve(puzzle, solver) if (results == None): solver = "BTS" results = Sudoku.solve(puzzle, solver) print(solver, puzzle) if (results == None): Reporter.write_output( file_name = output_csv_file_name, content = "\n", ) else: # write lines to output file Reporter.write_output( file_name = output_csv_file_name, content = " ".join([results, solver]) + "\n", )
def test_should_not_validate_board_with_repeated_elements_in_small_3x3( self): r1 = [i for i in range(1, 10)] r2 = [0, 0, 1, 0, 5, 0, 0, 0, 9] sudoku = Sudoku([r1] + [[0 for _ in range(9)]] + [r2] + [[0 for _ in range(9)] for _ in range(6)]) self.assertFalse(sudoku.is_valid_board())
def t_tester(solver_a, solver_b, verbose=False, difficulty='easy', trials=10): board = get_sugoku_board(difficulty) solvers = [solver_a, solver_b] timers = [Timer(f.__name__) for f in solvers] for timer, solver in zip(timers, solvers): solver_guesses = [] for _ in range(trials): game = Sudoku(board) empty = game.number_empty() timer.start() done, guesses = solver(game) timer.stop(verbose=verbose) if not done: print('unsolved') else: solver_guesses.append(guesses / empty) print("{:50}: Avg Number of Percentage Guess: {:.5f}".format( solver.__name__, stat.mean(solver_guesses))) for timer in timers: timer.summary() print(sci_stats.ttest_rel(timers[0].times, timers[1].times)) return 0
def test_board_print_9x9(self): sudoku = Sudoku("53■■7■25■" "■6■■195■■" "■■98■■■■6" "■8■■■6■■■" "34■■8■3■■" "17■■■2■■■" "6■6■■■■28" "■■■■419■■" "5■■■■8■■7") self.assertEqual( sudoku.printBoard(), "-------------------------------------\n" "| 5 3 ■ | ■ 7 ■ | 2 5 ■ |\n" "| - - - - - - - - |\n" "| ■ 6 ■ | ■ 1 9 | 5 ■ ■ |\n" "| - - - - - - - - |\n" "| ■ ■ 9 | 8 ■ ■ | ■ ■ 6 |\n" "|---+---+---+---+---+---+---+---+---|\n" "| ■ 8 ■ | ■ ■ 6 | ■ ■ ■ |\n" "| - - - - - - - - |\n" "| 3 4 ■ | ■ 8 ■ | 3 ■ ■ |\n" "| - - - - - - - - |\n" "| 1 7 ■ | ■ ■ 2 | ■ ■ ■ |\n" "|---+---+---+---+---+---+---+---+---|\n" "| 6 ■ 6 | ■ ■ ■ | ■ 2 8 |\n" "| - - - - - - - - |\n" "| ■ ■ ■ | ■ 4 1 | 9 ■ ■ |\n" "| - - - - - - - - |\n" "| 5 ■ ■ | ■ ■ 8 | ■ ■ 7 |\n" "-------------------------------------")
def test_game_not_over_2_9x9(self): sudoku = Sudoku("53■■7■■■■6■■195■■2■98■■■■6■8■■■6■■■34■■8■3■■1" "7■■■2■■■6■6■3■■28■■■■419■■5■■■■8■■79") self.assertTrue(sudoku.putNumber(4, 2, 4)) self.assertTrue(sudoku.putNumber(5, 3, 6)) self.assertTrue(sudoku.putNumber(3, 2, 4)) self.assertFalse(sudoku.isOver())
def solver(path, debug=False): model = load_model("MNIST_classifier_v2") image = cv2.imread(path) image = imutils.resize(image, width=600) try: (gridImage, warped) = find_grid(image, debug) except: return json.dumps("An error occurred, please try uploading a different image") board = np.zeros((9, 9), dtype="int") step_x = warped.shape[1] // 9 step_y = warped.shape[0] // 9 cells = [] for i in range(0, 9): row = [] for j in range(0, 9): start_x = j * step_x start_y = i * step_y end_x = (j + 1) * step_x end_y = (i + 1) * step_y #crop the cell from the warped transform image #extract the digit row.append((start_x, start_y, end_x, end_y)) cell = warped[start_y:end_y, start_x:end_x] digit = extract_digit(cell, debug) if digit is not None: #resize the cell to 28x28 and do preprocessing for classification roi = cv2.resize(digit, (28, 28)) roi = roi.astype("float") / 255.0 roi = img_to_array(roi) roi = np.expand_dims(roi, axis=0) prediction = model.predict(roi).argmax(axis=1)[0] board[i, j] = prediction cells.append(row) print("OCR Sudoku Grid:") grid = Sudoku(3, 3, board=board.tolist()) grid.show() print(grid.board) elements = 0 for m in grid.board: for n in m: if n == None: elements += 1 if elements == 81: return json.dumps("Not a Sudoku puzzle.") else: print("Solving...") solution = grid.solve() solution.show_full() final = json.dumps(solution.board) return final '''SHOW SOLUTION ON IMAGE
def solve_sudoku(board): board = np.array(board).reshape((9, 9)) print(board) board = board.tolist() puzzle = Sudoku(3, 3, board=board) print(puzzle) return puzzle.solve()
def test_sudoku_p0(): print "\nTest Sudoku p0" sd2 = Sudoku() idx = [1, 3, 6, 8, 9, 11, 14, 16] val = [1, 3, 4, 2, 4, 2, 1, 3] idx = idx[:0] val = val[:0] mat_set = sd2.make_sudoku_matrix(pre_set=(idx, val)) row, col = mat_set.shape print "size %s %s" % (row, col) b = np.ones(row) c = np.zeros(col) A = mat_set.toarray() ## scipy linprog cur = time.time() ret = optimize.linprog(c, A_eq=A, b_eq=b) print "\nScipy time cost %5s" % (time.time() - cur) mat = sd2.vec2mat(ret.x) print ret print "Sudoku Matrix\n%s" % str(mat) ## simplex LU num_slack = row c = np.concatenate((c, np.ones(row))) A = np.concatenate((A, np.eye(row)), axis=1) basis = range(col, col+row) cur = time.time() opt = simplex_revised(c, A, b, basis, eps=1e-10, max_iter=1000) print "\nSimplexLU time cost %5s" % (time.time() - cur) mat = sd2.vec2mat(opt.x_opt) print opt print "Sudoku Matrix\n%s" % str(mat)
def test_exclude_equal_alternatives(): EEA_1ST_ROW_ALTERNATIVES = [ {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 6, 5}, {1, 2, 3, 4, 7, 8, 9}, {1, 2, 3, 4, 8, 9, 7}, {1, 2, 3, 4, 9, 7, 8} ] EEA_1ST_ROW_ALTERNATIVES_SOLUTION = [ {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}, {6, 5}, {6, 5}, {7, 8, 9}, {8, 9, 7}, {9, 7, 8} ] grid_view = [[_cell_from_alternatives(EEA_1ST_ROW_ALTERNATIVES[i]) if j == 0 else Cell() for i in range(9)] for j in range(9)] Sudoku._Sudoku__exclude_equal_alternatives(grid_view) assert [cell._Cell__alternatives for cell in grid_view[0]] == EEA_1ST_ROW_ALTERNATIVES_SOLUTION # проверяем альтернативы в первой строке assert all([grid_view[i][j]._Cell__alternatives == {1, 2, 3, 4, 5, 6, 7, 8, 9} for j in range(9)] for i in range(1,9)) # проверяем, что альтернативы в других строках не изменлись
def reset(self): Sudoku.randominit(self, int(self.entrylist[81].get())) s=self.get() for i in range(0,9): for j in range(0,9): start[i][j]=s[i][j] self.reload(1)
def timedSolve(sudoku): """ timedSolve() solves a given sudoku puzzle with a time limit set by the timout decorator above. The @func_set_timeout decorator throws an error if the solve takes longer than x seconds. This prevents impossible to solve sudokus from choking the system. @params sudoku : 2d list of ints @returns board : 2d list of ints """ start = time.time() puzzle = Sudoku(3, 3, board=sudoku) solution = puzzle.solve() stop = time.time() if not puzzle.validate(): return None print("Solved in:", stop - start, "seconds") board = solution.board return board
def solve_sudoku(filename, filename_out=None): """Open a sudoku located in filename and solve it. If filename_out is not None, the solved sudoku is saved. Arguments: filename -- the file name Keyword arguments: filename_out -- the output file name (default None) """ board = Board(filename=filename) draw_board(board) print _(u"Solving sudoku..."), sys.stdout.flush() # Use all the algos sudoku = Sudoku(board, difficulty="hard") success = False if sudoku.solve(): print _(u"success!") success = True else: print _(u"can't be solved!") draw_board(sudoku.to_board()) if filename_out: sudoku.to_board().save(filename_out) return success
def test_revise_5(): puzzle = ( "" + "000000042" + "000000031" + "000000000" # here + "567800000" + "000000024" + "000000013" + "000000000" + "000000000" + "000000000" ) index = Sudoku.get_index((2, 6)) neighbor_index = Sudoku.get_index((3, 6)) index_domains = Sudoku.get_domains_for_index(puzzle, index) neighbor_domains = Sudoku.get_domains_for_index(puzzle, neighbor_index) assert index_domains == set([5, 6, 7, 8, 9]) assert neighbor_domains == set([9]) assert index == 24 result = Sudoku.revise_domains(puzzle, index, neighbor_index) assert result == (set([5, 6, 7, 8]), True)
class SudokuDocument(object): def __init__(self, dim=3): self._notifiers = set([]) self._doc = Sudoku(dim=dim) def ImportHex(self, text): try: val = int(text[-2:]) except: return False if not self.setDim(val): return False self._doc.ImportHex(text[0:-2]) return True def ExportHex(self): return '%s%02d' % (self._doc.ExportHex(), self._doc.dim) def open(self, change_notifier): t = (change_notifier, ) self._notifiers.add(t) return t def close(self, t): self._notifiers.remove(t) def items(self): populated = 0 fixed = 0 for e in self._doc.data: if e.HasVal(): populated += 1 if e.fixed: fixed += 1 return (fixed, populated) def setDim(self, dim): if dim != self._doc.dim: self._update(Sudoku(dim=dim)) return True return False def setval(self, idx, val, fixed=None): self._doc.data[idx].setval(val) def clear(self, force=None): for x in self._doc.data: if not x.fixed or force: x.setval(None) def _update(self, doc): self._doc = doc for t in self._notifiers: notifier = t[0] notifier() @property def doc(self): return self._doc
def setUp(self): self.orig_board = ([ "53xx7xxxx", "6xx195xxx", "x98xxxx6x", "8xxx6xxx3", "4xx8x3xx1", "7xxx2xxx6", "x6xxxx28x", "xxx419xx5", "xxxx8xx79" ]) self.orig_board_44 = (["x2xx", "3xx1", "x32x", "4xxx"]) self.game = Sudoku(self.orig_board) self.game44 = Sudoku(self.orig_board_44)
def test_sudoku_default_constructor(): s = Sudoku() for i in range(sConstants.dimension): for j in range(sConstants.dimension): cell = s.get_cell(i, j) if cell not in sConstants.valid_cells: raise ValueError
def test_iter_rows(self, data: Sequence[Sequence[int]]) -> None: s = Sudoku(data) rows_iter = s._iter_rows() for row, expected_row in zip(rows_iter, data): assert row == expected_row with pytest.raises(StopIteration): next(rows_iter)
def test_constructor_fail(self): """Test TypeErrors are raised for garbage in""" with self.assertRaises(TypeError): Sudoku("nonsense") with self.assertRaises(TypeError): Sudoku(1) with self.assertRaises(TypeError): Sudoku(solveable_list[-1])
def test_solve(self): # Setup sudoku = Sudoku(puzzle=PUZZLE) # Run sudoku.solve() # Verify self.assertEqual(sudoku.puzzle, PUZZLE) self.assertEqual(sudoku.solution, SOLUTION)
def solve(s: Sudoku): pos = s.getFirstFreePosition() if pos is None: return s x, y = pos for v in range(1, 10): if s.isMoveCorrect(x, y, v): newS = s.clone() newS.setAtPosition(x, y, v) solved = solve(newS) if solved is not None: return solved return None
def test_read_string(): str1 = " , 9, , , , , 2, , 5;\n" + \ "2, , , 3, , , 8, 9, ;\n" + \ " , , , , 2, 5, , 7, ;\n" + \ " , , 1, , 6, , , , 2;\n" + \ " , 3, , , 9, , , 5, ;\n" + \ "9, , , , 1, , 4, , ;\n" + \ " , 5, , 7, 4, , , , ;\n" + \ " , 6, 3, , , 8, , , 9;\n" + \ "7, , 4, , , , , 6, ;\n" sudoku = Sudoku() sudoku.read_string(str1) assert_equal(str(sudoku), str1)
def test_incorrect_sudoku(): incorrect = "1, 2, 3, , , , , , ;\n" + \ "4, 5, 6, , , , , , ;\n" + \ "7, 8, , 9, , , , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" sudoku = Sudoku() sudoku.read_string(incorrect) sudoku.recursive_solve()
class Test(unittest.TestCase): def setUp(self): str_sudoku = """003020600 900305001 001806400 008102900 700000008 006708200 002609500 800203009 005010300""" int_sudoku = [] for line in str_sudoku.split("\n"): int_sudoku.append([int(i) for i in list(line.strip())]) self.s = Sudoku(int_sudoku) def testGetRowCells(self): print "-------------" for i in range(9): result = self.s.get_row_cells(i) for cell in result: print cell.value, print "" def testGetColCells(self): print "-------------" for j in range(9): result = self.s.get_col_cells(j) for cell in result: print cell.value, print "" def testGetColCells(self): print "-------------" for i in range(0, 9, 3): for j in range(0, 9, 3): result = self.s.get_sect_cells(i, j) for cell in result: print cell.value, print "" def testGetCellPositionInSect(self): print "-------------" print "testGetCellPositionInSect" for i in range(0, 9, 3): for j in range(0, 9, 3): for cell_place in range(9): print "i, j, cell_place --> result: %s, %s, %s, %s" % (i, j, cell_place, self.s.get_cell_position_in_sect(i, j, cell_place)) print "-------------"
def solve(self): # Read values from the grid values = [[self.get_value(row, col) for col in range(9)] for row in range(9)] # Try to solve the Sudoku solver = Sudoku(values) if solver.solve(): for row in range(9): for col in range(9): self.text_inputs[9 * row + col].text = str(solver.get_value(row, col)) else: error_message = ErrorMessage() self.error_messages.append(error_message) self.add_widget(error_message) Clock.schedule_once(self.remove_error_message, 2)
def gen_test(file_name): """Функция генерирует тест-case из файла """ in_file = open(file_name) size = int(in_file.readline()) in_file.close() sudoku = Sudoku(size, False) gb = sudoku.load_gb_from_file(file_name) def test_func(self): self.assertTrue(sudoku.get_solution(gb)) self.assertTrue(sudoku.is_solution(gb)) return test_func
def main(): sudoku = Sudoku(3) print(sudoku) # sudoku.feed([1,2,4,3,3,None,None,None,2,1,3,None,None,3,2,1]) # test #sudoku.feed([None,7,5,None,9,None,None,None,6,None,2,3,None,8,None,None,4,None,8,None,None,None,None,3,None,None,1,5,None,None,7,None,2,None,None,None,None,4,None,8,None,6,None,2,None,None,None,None,9,None,1,None,None,3,9,None,None,4,None,None,None,None,7,None,6,None,None,7,None,5,8,None,7,None,None,None,1,None,3,9,None]) # rem #sudoku.feed([None,5,None,None,None,None,2,8,None,None,None,None,None,7,6,None,None,None,None,None,2,1,None,None,None,None,None,9,4,None,None,1,None,None,None,None,None,None,1,5,None,4,None,None,None,None,None,6,None,None,3,9,None,None,6,None,None,3,None,None,None,None,None,None,2,None,7,None,1,6,4,None,None,None,None,None,None,None,5,None,3]) sudoku.feed([5,4,8,None,6,None,None,None,None,None,None,None,5,None,None,None,None,2,None,None,None,3,None,4,None,7,None,7,None,1,None,None,None,None,None,None,2,9,None,None,None,None,1,5,4,None,3,5,None,None,None,None,9,None,6,2,None,None,None,None,None,1,None,None,None,None,None,None,None,None,6,None,9,None,None,None,None,3,4,None,None]) print(sudoku) solver = Solver(sudoku) solved = solver.solve() if solved: print("SOLVED !!") print(sudoku) sudoku.printIncertitudes()
def test_solved_puzzle_is_solved(self): """example taken from http://www.sudokugame.com/rules.php""" tmp = Sudoku() tmp[0] = [2,4,8,3,9,5,7,1,6] tmp[1] = [5,7,1,6,2,8,3,4,9] tmp[2] = [9,3,6,7,4,1,5,8,2] tmp[3] = [6,8,2,5,3,9,1,7,4] tmp[4] = [3,5,9,1,7,4,6,2,8] tmp[5] = [7,1,4,8,6,2,9,5,3] tmp[6] = [8,6,3,4,1,7,2,9,5] tmp[7] = [1,9,5,2,8,6,4,3,7] tmp[8] = [4,2,7,9,5,3,8,6,1] self.assertTrue(tmp.solved()) self.assertFalse(tmp.has_zero()) self.assertTrue(tmp.consistent())
class TestDLX(unittest.TestCase): def setUp(self): self.sudoku = Sudoku(validate=True, pretty=False) def read_line_by_line(self, filename, callback): lines = open(filename) for line in lines: self.assertEqual(len(line), 82) self.assertEqual(line[81], '\n') callback(line[:81]) def assert_exception(self, line): self.assertRaises(SudokuError, self.sudoku.solve, line) def assert_valid(self, line): grids = self.sudoku.solve(line) self.assertEqual(len(grids), 1) def test_bad_solutions(self): filename = 'tests/data/collections/bad' self.read_line_by_line(filename, self.assert_exception) def test_valid_solutions(self): filename = 'tests/data/collections/hardest' self.read_line_by_line(filename, self.assert_valid)
def __init__(self, size=3): Gtk.Window.__init__(self, title="Sudoku Example") self.size = size # This is an instance of a Sudoku solver self.sudoku = Sudoku(size) # Draw the window self.table = [[Gtk.Entry() for _ in xrange(size**2)] for _ in xrange(size**2)] vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.add(vbox) grid = Gtk.Grid() vbox.add(grid) for row,lst in enumerate(self.table): for col,entry in enumerate(lst): entry.set_max_length(3) entry.set_hexpand(True) entry.set_vexpand(True) entry.set_width_chars(2) grid.attach(entry, col, row, 1, 1) self.solve_button = Gtk.Button(label="Solve") self.solve_button.set_hexpand(True) vbox.add(self.solve_button) self.solve_button.connect("clicked", self.solve) self.clear_button = Gtk.Button(label="Clear") self.clear_button.set_hexpand(True) vbox.add(self.clear_button) self.clear_button.connect("clicked", self.clear)
def onCargajuegoClicked(self): """Nos permite Cargar un juego anteriormente guardado""" (nombre,ok) = QInputDialog.getText(self, self.tr("Sudoku"), self.tr("Nombre:"),QLineEdit.Normal, self.tr("")) if ok==True: while str(nombre)=="" and ok==True: self.MessageBox(None,"Ingrese Un Nombre..!","ERROR",self.MB_ICONERROR) (nombre,ok) = QInputDialog.getText(self, self.tr("Sudoku"), self.tr("Nombre:"),QLineEdit.Normal, self.tr("")) if ok==True: archivo=open("Partidas.txt","r") linea=archivo.readline() Existe=0 while linea!="": partida=linea.split(",") nombreG=partida[0] if str(nombre)==nombreG: Existe=1 break linea=archivo.readline() if Existe==1: invalida=partida[3] incorrecta=partida[4] ayuda=partida[5] self.n= Sudoku(5,invalida,incorrecta,ayuda,partida) self.n.setVisible(True) self.close() else: self.MessageBox(None,"No Se Encontro El Archivo..!","ERROR",self.MB_ICONERROR) archivo.close()
def _colouring(s, poss, doubles, verbose=0): changes = 0 group_a = [] group_b = [] for [d1, d2] in doubles: if d1 in group_a: group_b.append(d1) group_a.append(d2) elif d1 in group_b: group_a.append(d1) group_b.append(d2) # for loc in set(group_a) & set(group_b): # if poss in s.fields[loc]: # changes += 1 # s.fields[loc].remove(poss) # if changes: # return changes for group in (group_a, group_b): rows = [] cols = [] for loc in group: r, c = Sudoku.i2rc(loc) if r in rows or c in cols: changes += _eliminate_group(s, poss, group, verbose) break rows.append(r) cols.append(c) return changes
def test_puzzlefy_l33t(self): # Setup sudoku = Sudoku(solution=SOLUTION, level="l33t") # Run sudoku.puzzlefy() # Verify empty_cells = sudoku.puzzle.count("0") self.assertLessEqual(empty_cells, MAX_EMPTY_CELLS_L33T) self.assertEqual(sudoku.solution, SOLUTION) # Run sudoku.solve() # Verify self.assertEqual(sudoku.solution, SOLUTION)
def create_sudoku(filename): """Create a sudoku with handicap and save it to filename. The handicap are the extra numbers given. Arguments: filename -- the file name """ while True: print _(u"Creating sudoku..."), sys.stdout.flush() sudoku = Sudoku(Board((options.getint("sudoku", "region_width"), options.getint("sudoku", "region_height"))), difficulty=options.get("sudoku", "difficulty")) sudoku.create(options.getint("sudoku", "handicap")) if options.getboolean("sudoku", "force") and \ (difficulty(sudoku.to_board()) != options.get("sudoku", "difficulty")): print _(u"sudoku with wrong difficulty!") else: sudoku.to_board().save(filename) print _(u"success!") break draw_board(sudoku.to_board()) return True
class Nuevojuego(QMainWindow): def __init__(self): """Contructor Setea uno de los dos checkbox de alertas en true y anade el fondo a la ventana.""" QMainWindow.__init__(self) self.ui= Ui_NuevoJuego() self.ui.setupUi(self) self.ui.pBJugar.clicked.connect(self.onPbjugarClicked) self.ui.pBCancelar.clicked.connect(self.onPbcancelarClicked) self.MessageBox= ctypes.windll.user32.MessageBoxA self.MB_ICONERROR = 0x00000010L #Critical Icon def onPbjugarClicked(self): """Despliega la ventana con el tablero para empezar el juego *Crea una instancia de la clase Sudoku y la muestra. *Verificara que se halla escogido un solo nivel de dificultad. *Verificara que halla escogido al menos una opcion de alerta.""" facil=self.ui.rBFacil.isChecked() medio=self.ui.rBMedio.isChecked() dificil=self.ui.rBDificil.isChecked() experto=self.ui.rBExperto.isChecked() invalida=self.ui.cbInvalidas.isChecked() incorrecta=self.ui.cbIncorrectas.isChecked() ayuda=self.ui.cbhelp.isChecked() if facil==False and medio==False and dificil==False and experto==False: self.MessageBox(None,"Seleccione Un Nivel De Dificultad..!","ERROR",self.MB_ICONERROR) elif invalida==False and incorrecta==False: self.MessageBox(None,"Seleccione al menos una opcion de alertas..!","ERROR",self.MB_ICONERROR) elif facil: self.n= Sudoku(1,invalida,incorrecta,ayuda,"") self.n.setVisible(True) self.close() elif medio: self.n= Sudoku(2,invalida,incorrecta,ayuda,"") self.n.setVisible(True) self.close() elif dificil: self.n= Sudoku(3,invalida,incorrecta,ayuda,"") self.n.setVisible(True) self.close() elif experto: self.n= Sudoku(4,invalida,incorrecta,ayuda,"") self.n.setVisible(True) self.close() def onPbcancelarClicked(self): """Despliega la ventana anterior Crea una instancia de la ventana principal y la muestra""" from principal import Principal self.p= Principal() self.p.setVisible(True) self.close()
def sudoku_api(original): s = Sudoku() s.load_data_from_argv(original) cursor = 0 s.pre_calculate() solve_sudoku(s) return s.get_list_value()
def test_sudoku_should_resolve_an_easy_sudoku_with_backtracking_from_TXT_to_result(self): sudoku_test = Sudoku() settings_test = Settings() expected_result= ["4 8 3 |9 2 1 |6 5 7 \n", \ "9 6 7 |3 4 5 |8 2 1 \n", \ "2 5 1 |8 7 6 |4 9 3 \n", \ "------+------+------\n", \ "5 4 8 |1 3 2 |9 7 6 \n", \ "7 2 9 |5 6 4 |1 3 8 \n", \ "1 3 6 |7 9 8 |2 4 5 \n", \ "------+------+------\n", \ "3 7 2 |6 8 9 |5 1 4 \n", \ "8 1 4 |2 5 3 |7 6 9 \n", \ "6 9 5 |4 1 7 |3 8 2 \n"] settings_test.set_config("Algorithm", "Backtracking") settings_test.set_config("Input", "TXT") settings_test.write_settings() sudoku_test.start_game() file_result = open("../game_results/default.txt", 'r') result = file_result.readlines() file_result.close() self.assertEqual(expected_result, result)
def test_single_possibility(): one_poss = "1, , , , , , , , ;\n" + \ " , , , 1, , , , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , 1, ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , 1;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" solution = "1, , , , , , , , ;\n" + \ " , , , 1, , , , , ;\n" + \ " , , , , , , 1, , ;\n" + \ " , , , , , , , 1, ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , 1;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" sudoku = Sudoku() sudoku.read_string(one_poss) sudoku.solve() assert_equal(str(sudoku), solution)
def newGame(self, name, elapsedSeconds = 0, sudoku = None): """Se genera un nuevo juego de sudoku con el nombre del jugador y el nivel.""" if sudoku == None: self.sudoku = Sudoku() self.sudoku.shuffle(self.difficulty*9 + 3*9) else: self.sudoku = sudoku self.sudoku.cellValueChanged.connect(self.setCellValue) self.sudoku.triggerChanges() self.sudoku.cellValueChanged.disconnect(self.setCellValue) """Actualiza el modelo cuando la vista es cambiada.""" self.cellValueChanged.connect(self.sudoku.setCellValue) self.initTimer(elapsedSeconds) self.ui.btnJugador.setText(name)
def test_hidden_twins(): boxPair = " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , 3, , 5, 6, , , ;\n" + \ " , , , , 7, 8, 3, , ;\n" + \ " , , , 4, , , , , ;\n" + \ " , , , 9, , , , , ;\n" + \ " , , , , , , , , ;\n" solution = " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , , 3, , , , , ;\n" + \ " , , 3, , 5, 6, , , ;\n" + \ " , , , , 7, 8, 3, , ;\n" + \ " , , , 4, , , , , ;\n" + \ " , , , 9, , , , , ;\n" + \ " , , , , , , , , ;\n" sudoku = Sudoku() sudoku.read_string(boxPair) sudoku.solve() assert_equal(str(sudoku), solution)
def test_subgroup_exclusion(): intBoxColumn = " , , , , , , 4, 5, ;\n" + \ " , , , , , , 6, 7, ;\n" + \ " , , , , , 1, , 9, 8;\n" + \ " , , , , , , , 2, 9;\n" + \ " , , , , , 3, , , ;\n" + \ " , , , , , , , , 4;\n" + \ " , , , , , , , , 5;\n" + \ " , , , , , , , , 6;\n" + \ " , , , , , , , , ;\n" solution = " , , , , , , 4, 5, ;\n" + \ " , , , , , , 6, 7, ;\n" + \ " , , , , , 1, , 9, 8;\n" + \ " , , , , , , , 2, 9;\n" + \ " , , , , , 3, , , 7;\n" + \ " , , , , , , , , 4;\n" + \ " , , , , , , , , 5;\n" + \ " , , , , , , , , 6;\n" + \ " , , , , , , , , ;\n" sudoku = Sudoku() sudoku.read_string(intBoxColumn) sudoku.solve() assert_equal(str(sudoku), solution)
def test_only_choice(): one_choice = " , , , , 3, 4, , , ;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , 2, , 5;\n" + \ " , , , , , , , , 6;\n" + \ " , , , , , , , , 7;\n" + \ " , , , , , , , , 8;\n" + \ " , , , , , , , , 9;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" solution = " , , , , 3, 4, , , 1;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , 2, , 5;\n" + \ " , , , , , , , , 6;\n" + \ " , , , , , , , , 7;\n" + \ " , , , , , , , , 8;\n" + \ " , , , , , , , , 9;\n" + \ " , , , , , , , , ;\n" + \ " , , , , , , , , ;\n" sudoku = Sudoku() sudoku.read_string(one_choice) sudoku.solve() assert_equal(str(sudoku), solution)
def loadFromFile(): filename = 'savedgames' if not os.path.isfile(filename): open(filename, 'w').close() f = LamecryptFile(filename, 'r') games = [] for strG in f.read().split("\n"): g = strG.split(':') if len(g) == 3: games.append( Game(g[0], int(g[1]), Sudoku.fromString(g[2])) ) return games