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 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_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 setUp(self): self.instancia_uno = Sudoku(1) self.instancia_dos = Sudoku(2) self.instancia_tres = Sudoku(3) self.instancia_uno.cargarTablero() self.instancia_dos.cargarTablero() self.instancia_tres.cargarTablero()
def setUp(self): self.hardest = Sudoku(HARDEST) self.easy = Sudoku(EASY) self.medium = Sudoku(MEDIUM) self.hard = Sudoku(HARD) self.evil = Sudoku(EVIL) self.correct = Sudoku(CORRECT) self.incorrect = Sudoku(INCORRECT) self.impossible = Sudoku(IMPOSSIBLE) self.easy_4x4 = Sudoku(EASY_4x4) self.easy_16x16 = Sudoku(EASY_16x16)
def read_sudokus(file_path): with open(file_path, "r") as f: for line in f: line = line.strip() if "Grid" in line: if line[-2:] != "01": yield Sudoku(grid) grid = [] else: row = [int(digit) for digit in line] grid.append(row) yield Sudoku(grid)
def test_solved(self): """Test that my solution checker works.""" # this is unsolved self.assertFalse(Sudoku(solveable_list).is_solved()) # and this is solved presolved = [[5, 1, 3, 6, 8, 7, 2, 4, 9], [8, 4, 9, 5, 2, 1, 6, 3, 7], [2, 6, 7, 3, 4, 9, 5, 8, 1], [1, 5, 8, 4, 6, 3, 9, 7, 2], [9, 7, 4, 2, 1, 8, 3, 6, 5], [3, 2, 6, 7, 9, 5, 4, 1, 8], [7, 8, 2, 9, 3, 4, 1, 5, 6], [6, 3, 5, 1, 7, 2, 8, 9, 4], [4, 9, 1, 8, 5, 6, 7, 2, 3]] self.assertTrue(Sudoku(presolved).is_solved())
def __init__(self): parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", help="Path to the file containing the sudoku") args = parser.parse_args() if args.file is not None: sudoku = Sudoku(Parser.parse(args.file)) else: print("Using default sudoku file") sudoku = Sudoku( Parser.parse(Main.resource_path("exemples/easy_1.txt"))) Display(sudoku)
def setUp(self): self.zero_arr = empty_grid() self.complete_arr = complete_grid() self.missing_1_arr = missing_1() self.missing_3_arr = missing_3() self.z = Sudoku() # Homogenous grid self.u = Sudoku() # All-unique grid self.c = Sudoku() # Valid, complete grid self.t = Sudoku() # Partially complete grid - missing 3 #s self.o = Sudoku() # Partially complete grid - missing 1 # self.z.grid = np.full((9, 9), 0) self.u.grid = unique_grid() self.c.grid = complete_grid() self.t.grid = missing_3() self.o.grid = missing_1()
def __init__(self, game: str = None) -> None: if game: lines = game.split('\n') self.base = list(map(int, lines[0].split())) board = [[int(lines[1][i * 9 + j]) or None for j in range(9)] for i in range(9)] self.game = Sudoku(3, board=board) else: seed = random.randrange(sys.maxsize) self.game = Sudoku(3, seed=seed).difficulty(0.5) self.base = [] for i, row in enumerate(self.game.board): for j, n in enumerate(row): if n: self.base.append(i * 9 + j)
def Main(): # hard coded grid solving # for hell level, the number of solutions is extremly high print("\n\n Grid resolution : \n\n") s1 = Sudoku(initial_board=sudoku_hell) s1.Solve(solution_limit=20) print("\n\n Grid generation : \n\n") # automatic grid generation and solving with difficulty parameter oneOf(beginner, easy, medium, hard, hell) difficulty = 'hell' automatic_grid = Get_solvable_grid(difficulty) Display_grid(automatic_grid, difficulty) print("\nRésolution du Sudoku : \n") s2 = Sudoku(initial_board=automatic_grid) s2.Solve(solution_limit=20)
def main(): # Ensure proper usage if len(sys.argv) != 2: sys.exit("Usage: python runner.py file") # Get a game from a file filename = sys.argv[1] with open(filename) as f: contents = f.read() # Assemble a board (9x9 array) with the data contents = contents.splitlines() board = [] for i in range(HEIGHT): row = [] for j in range(WIDTH): try: row.append(int(contents[i][j])) except: row.append(False) board.append(row) #print(board) #Starts a new game object #game = Sudoku(height=HEIGHT, width=WIDTH) game = Sudoku(board, height=HEIGHT, width=WIDTH) print("Game:") game.print() #Try to solve the game game.solve()
def eval_sudoku(array): #return sum(array) # un-comment this line and watch the GA optimize to all max numbers #return -sum(array) # un-comment this line and watch the GA optimize to all ones s = Sudoku(0) size = int(math.sqrt(len(array))) s.set_arr(array) fitness = 0 # count unique values in each row for r in range(s.size()): vals = set() for c in range(s.size()): vals.add(s.get(r, c)) fitness += len(vals) # count unique values in each column for c in range(s.size()): vals = set() for r in range(s.size()): vals.add(s.get(r, c)) fitness += len(vals) # count unique values in each square sqsize = int(math.sqrt(s.size())) for sr in range(sqsize): for sc in range(sqsize): vals = set() for r in range(sqsize): for c in range(sqsize): vals.add(s.get(sr * sqsize + r, sc * sqsize + c)) fitness += len(vals) return fitness
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 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 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 main(): with open("sudHard.txt") as entrada: matriz = [] linhas = entrada.readlines() for linha in linhas: #O formato mais legível para o sudoku inclui tanto ' ' quanto '|' como delimitadores, e por isso STRING.split() não foi usado. O módulo RE (Expressões Regulares) faz um trabalho chato em uma linha legível de código. 5/5! #Busque todo padrão de tamanho 1 composto por caracteres númericos, ou seja, busque só os digitos. linha = findall("\d", linha) if linha: linha = [int(i) for i in linha] matriz.append(linha) sudoku1 = Sudoku(matriz) sudoku2 = deepcopy(sudoku1) expan, backt = buscaBacktracking(sudoku1) print(sudoku1) print(f'EXPANSÕES: {expan}') print(f'BACKTRACKS: {backt}') niter = minimosConflitos(sudoku2) print(niter) print(sudoku2) print(f'ITERAÇÕES: {niter}')
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.unassigned = [] # list of unassigned cells as tuples (row, col) 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 possibilities. 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 __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 is_valid(self, i: int, j: int, value: int) -> bool: if i*9+j in self.base or not 0 <= i <= 8 or \ not 0 <= j <= 8 or not 0 <= value <= 9: return False board = self.game.board.copy() board[i][j] = value return Sudoku(3, 3, board=board).validate()
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_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 main(): if len(sys.argv) != 2: usage() try: puzzle = SUDOKUS[sys.argv[1]] except: usage() os.system("clear") print("Loading...") surface, screen = initPygame() clock = pygame.time.Clock() myfont = pygame.font.SysFont("arialblack", 35) settings = Settings(surface, screen, clock, myfont) os.system("clear") sudoku = Sudoku(puzzle) sudoku.showSudoku(settings) while True: handleKeys(settings) if settings.start and not settings.finished: os.system("clear") if sudoku.solve(settings): print("SOLVED") else: print("UNSOLVABLE") settings.finished = True settings.start = False elif settings.start and settings.finished: sudoku.state = np.array(sudoku.starting_state) sudoku.showSudoku(settings) settings.finished = False settings.start = False
def parse_sudoku(data): sudoku = Sudoku( np.array(list(map(int, data)), dtype=np.uint8).reshape([9, 9])) if not sudoku.valid: raise ValueError( 'Invalid sudoku configuration found in dataset') return sudoku
def main(): from sudoku import Sudoku grid = [[i for i in range(1, 10)] for i in range(1, 10)] s = Sudoku(grid) clean(grid, 50) print(s)
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 generate(self): # init an empty game emptyGame = Sudoku() # solve it randomly solver = SudokuSolver(emptyGame, enableRandom=True) solution = solver.sudoku # choose the cells to cleanup randomly cellIndices = random.sample( range(solution.numberOfRows * solution.numberOfCols), self.maxEmptyCells) # init the generated game as solution generatedGame = copy.deepcopy(solution) # iteratively try pop the cells for cellIndex in cellIndices: # get the cell using index and backup value cell = generatedGame.getCell( cellIndex // generatedGame.numberOfCols, cellIndex % generatedGame.numberOfCols) valueToBackup = cell.val # replace the value with SudokuCellValue.EMPTY cell.val = SudokuCellValue.EMPTY # if the solution is not unique after SudokuCellValue.EMPTY is filled, just simply revert the action if not SudokuSolver(generatedGame).isSolutionUnique: cell.val = valueToBackup # return the game and solution return (generatedGame, solution)
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_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 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