def Solver(puzzle, r, c, search="bfs", printSolution=False): if search == "bfs": call = BFS(Sudoku(puzzle, len(puzzle), r, c)) elif search == "dfs": call = DFS(Sudoku(puzzle, len(puzzle), r, c)) else: call = "Invalid search" if printSolution: if call == None: print("No Solution") return call else: return call
def sudoku_solver(sudoku): """ Solves a Sudoku puzzle and returns its unique solution. Input sudoku : 9x9 numpy array of integers Empty cells are designated by 0. Output 9x9 numpy array of integers It contains the solution, if there is one. If there is no solution, all array entries should be -1. """ # First complete constraint propagation s = Sudoku(sudoku) s.solve() # Return complete board or start backtracking if s.check_complete(): return (s.get_board()) else: s = s.continue_solve() if s.check_complete(): return s.get_board() else: unsolveable = np.full((s.get_size(), s.get_size()), -1, dtype=int) return unsolveable
def solve_sudoku_extra(puzzle): # for testing, always initialize the pseudorandom number generator to output the same sequence # of values: random.seed(41) puzzle_name = str(puzzle) sol_filename = puzzle_name[:-4] + ".sol" sat = SAT(puzzle) start = time.time() result = sat.WalkSAT() total = time.time() - start if puzzle_name[-4:] == ".sud": print("original sudoku puzzle: ") sud = Sudoku() sud.load(puzzle) print(sud) if result: sat.sol_file(sol_filename) print("solution found in " + str(sat.runs) + " iterations of SAT") print("the code took " + str(total) + " seconds to run.") display_sudoku_solution(sol_filename) else: print("no solution found by SAT in " + str(sat.limit) + " iterations of SAT")
def __init__(self, screen): """ Initializes the game application """ self._grid = Sudoku() # self._screen = screen padding = 20 width, height = screen.get_size() self._text_grid = [[None for _ in range(9)] for _ in range(9)] # Create a Textbox for each cell of the grid for row in range(9): for col in range(9): self._text_grid[row][col] = \ Textbox((width - 2 * padding) * col / 9 + padding, (height - 2 * padding) * row / 9 + padding, (width - 2 * padding) * 1 / 9, (height - 2 * padding) * 1 / 9) # Reads the grid model and displays each cell on the screen for row in range(9): for col in range(9): # 0 is seen as an empty space, and the clues if self._grid.get_cell(row, col) != 0: self._text_grid[row][col].set_text(self._grid.get_cell(row, col)) self._text_grid[row][col].set_editable(False) self._update_tile()
def __init__(self, handle): super(PeterActivity, self).__init__(handle) # Build the activity toolbar. toolbox = activity.ActivityToolbox(self) activity_toolbar = toolbox.get_activity_toolbar() activity_toolbar.keep.props.visible = False activity_toolbar.share.props.visible = False toolbox.show() self.set_toolbox(toolbox) # Create the game instance. self.game = Sudoku.Sudoku() # Build the Pygame canvas. self._pygamecanvas = \ sugargame.canvas.PygameCanvas(self) # Note that set_canvas implicitly calls # read_file when resuming from the Journal. self.set_canvas(self._pygamecanvas) self.game.canvas = self._pygamecanvas # Start the game running. self._pygamecanvas.run_pygame(self.game.run)
def test_check_results(self): puzzle = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] game = Sudoku(puzzle) self.asserter.assertTrue(game.check_results([1, 2, 3])) self.asserter.assertFalse(game.check_results([15, 2, 3]))
def test_is_finished(): s = Sudoku.Sudoku([[4, 1, 5, 6, 3, 8, 9, 7, 2], [3, 6, 2, 4, 7, 9, 1, 8, 5], [7, 8, 9, 2, 1, 5, 3, 6, 4], [9, 2, 6, 3, 4, 1, 7, 5, 8], [1, 3, 8, 7, 5, 6, 4, 2, 9], [5, 7, 4, 9, 8, 2, 6, 3, 1], [2, 5, 7, 1, 6, 4, 8, 9, 3], [8, 4, 3, 5, 9, 7, 2, 1, 6], [6, 9, 1, 8, 2, 3, 5, 4, 7]]) assert (s.is_resolved() is True)
def test_get_least_constraints(): s = Sudoku.Sudoku([[8, 0, 0, 0, 0, 0, 6, 0, 0], [9, 3, 0, 8, 0, 0, 0, 7, 1], [0, 2, 5, 0, 6, 3, 8, 0, 0], [0, 6, 1, 0, 0, 0, 0, 0, 0], [0, 9, 8, 4, 5, 6, 3, 1, 0], [0, 0, 0, 0, 0, 0, 4, 6, 0], [0, 0, 3, 9, 8, 0, 7, 5, 0], [7, 8, 0, 0, 0, 1, 0, 3, 6], [0, 0, 9, 0, 0, 0, 0, 0, 2]]) assert (s.get_mrv_cell() == {'score': 4, 'x': 4, 'y': 0})
def test_get_possibilities_for(): s = Sudoku.Sudoku([[8, 0, 0, 0, 0, 0, 6, 0, 0], [9, 3, 0, 8, 0, 0, 0, 7, 1], [0, 2, 5, 0, 6, 3, 8, 0, 0], [0, 6, 1, 0, 0, 0, 0, 0, 0], [0, 9, 8, 4, 5, 6, 3, 1, 0], [0, 0, 0, 0, 0, 0, 4, 6, 0], [0, 0, 3, 9, 8, 0, 7, 5, 0], [7, 8, 0, 0, 0, 1, 0, 3, 6], [0, 0, 9, 0, 0, 0, 0, 0, 2]]) assert (s.get_possibilities_for(0, 1) == [1, 4, 7])
def test_hash(): s = Sudoku.Sudoku([[8, 0, 0, 0, 0, 0, 6, 0, 0], [9, 3, 0, 8, 0, 0, 0, 7, 1], [0, 2, 5, 0, 6, 3, 8, 0, 0], [0, 6, 1, 0, 0, 0, 0, 0, 0], [0, 9, 8, 4, 5, 6, 3, 1, 0], [0, 0, 0, 0, 0, 0, 4, 6, 0], [0, 0, 3, 9, 8, 0, 7, 5, 0], [7, 8, 0, 0, 0, 1, 0, 3, 6], [0, 0, 9, 0, 0, 0, 0, 0, 2]]) assert (len(s.hash()) == 81)
def test_check_area(self): puzzle = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] game = Sudoku(puzzle) self.asserter.assertTrue(game.searches[0].isValid) game.change_number(0, 2, 3) game.check_area(0) self.asserter.assertFalse(game.searches[0].isValid)
def test_bad_square(): # bad square = 1, 1 s = Sudoku.Sudoku([[3, 0, 0, 0, 8, 0, 6, 0, 0], [9, 3, 0, 8, 0, 0, 0, 7, 1], [0, 2, 5, 0, 6, 3, 8, 0, 0], [0, 6, 1, 0, 0, 0, 0, 0, 0], [0, 9, 8, 4, 5, 6, 3, 1, 0], [0, 0, 0, 0, 0, 0, 4, 6, 0], [0, 0, 3, 9, 8, 0, 7, 5, 0], [7, 8, 0, 0, 0, 1, 0, 3, 6], [0, 0, 9, 0, 0, 0, 0, 0, 2]]) assert s.is_valid() is False
def test_get_forbidden_values_for(): s = Sudoku.Sudoku([[8, 0, 0, 0, 0, 0, 6, 0, 0], [9, 3, 0, 8, 0, 0, 0, 7, 1], [0, 2, 5, 0, 6, 3, 8, 0, 0], [0, 6, 1, 0, 0, 0, 0, 0, 0], [0, 9, 8, 4, 5, 6, 3, 1, 0], [0, 0, 0, 0, 0, 0, 4, 6, 0], [0, 0, 3, 9, 8, 0, 7, 5, 0], [7, 8, 0, 0, 0, 1, 0, 3, 6], [0, 0, 9, 0, 0, 0, 0, 0, 2]]) assert (s.get_forbidden_values_for(0, 0) is None) assert (s.get_forbidden_values_for(0, 1) == [3, 2, 6, 9, 8, 5])
def test_good_sudoku_from_array(): s = Sudoku.Sudoku([[8, 0, 0, 0, 0, 0, 6, 0, 0], [9, 3, 0, 8, 0, 0, 0, 7, 1], [0, 2, 5, 0, 6, 3, 8, 0, 0], [0, 6, 1, 0, 0, 0, 0, 0, 0], [0, 9, 8, 4, 5, 6, 3, 1, 0], [0, 0, 0, 0, 0, 0, 4, 6, 0], [0, 0, 3, 9, 8, 0, 7, 5, 0], [7, 8, 0, 0, 0, 1, 0, 3, 6], [0, 0, 9, 0, 0, 0, 0, 0, 2]]) assert type(s) is Sudoku.Sudoku assert s.is_valid() is True
def test_bad_col(): # bad col = col 1 s = Sudoku.Sudoku([[8, 0, 0, 0, 0, 0, 6, 0, 0], [9, 3, 0, 8, 0, 0, 0, 7, 1], [0, 2, 5, 0, 6, 3, 8, 0, 0], [0, 6, 1, 0, 0, 0, 0, 0, 0], [0, 9, 8, 4, 5, 6, 3, 1, 0], [8, 0, 0, 0, 0, 0, 4, 6, 0], [0, 0, 3, 9, 8, 0, 7, 5, 0], [7, 8, 0, 0, 0, 1, 0, 3, 6], [0, 0, 9, 0, 0, 0, 0, 0, 2]]) assert s.is_valid() is False
def test_check_for_win(self): puzzle = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] game = Sudoku(puzzle) self.asserter.assertFalse(game.check_for_win()) for i in range(9): for j in range(9): game.puzzle[i][j] = 1 self.asserter.assertTrue(game.check_for_win())
def test_break_sudoku(): s = Sudoku.Sudoku([[8, 0, 0, 0, 0, 0, 6, 0, 0], [9, 3, 0, 8, 0, 0, 0, 7, 1], [0, 2, 5, 0, 6, 3, 8, 0, 0], [0, 6, 1, 0, 0, 0, 0, 0, 0], [0, 9, 8, 4, 5, 6, 3, 1, 0], [0, 0, 0, 0, 0, 0, 4, 6, 0], [0, 0, 3, 9, 8, 0, 7, 5, 0], [7, 8, 0, 0, 0, 1, 0, 3, 6], [0, 0, 9, 0, 0, 0, 0, 0, 2]]) assert (s.is_valid()) s.set(0, 1, 8) assert (s.is_valid() is False)
def test_set(): s = Sudoku.Sudoku([[8, 0, 0, 0, 0, 0, 6, 0, 0], [9, 3, 0, 8, 0, 0, 0, 7, 1], [0, 2, 5, 0, 6, 3, 8, 0, 0], [0, 6, 1, 0, 0, 0, 0, 0, 0], [0, 9, 8, 4, 5, 6, 3, 1, 0], [0, 0, 0, 0, 0, 0, 4, 6, 0], [0, 0, 3, 9, 8, 0, 7, 5, 0], [7, 8, 0, 0, 0, 1, 0, 3, 6], [0, 0, 9, 0, 0, 0, 0, 0, 2]]) s.set(0, 1, 1) assert (s.get_sudoku() == [[8, 1, 0, 0, 0, 0, 6, 0, 0], [9, 3, 0, 8, 0, 0, 0, 7, 1], [0, 2, 5, 0, 6, 3, 8, 0, 0], [0, 6, 1, 0, 0, 0, 0, 0, 0], [0, 9, 8, 4, 5, 6, 3, 1, 0], [0, 0, 0, 0, 0, 0, 4, 6, 0], [0, 0, 3, 9, 8, 0, 7, 5, 0], [7, 8, 0, 0, 0, 1, 0, 3, 6], [0, 0, 9, 0, 0, 0, 0, 0, 2]])
def __init__(self, handle): Activity.__init__(self, handle) self.paused = False # Create the game instance. self.game = Sudoku.Sudoku() # Build the activity toolbar. self.build_toolbar() # Build the Pygame canvas and start the game running # (self.game.run is called when the activity constructor # returns). self._pygamecanvas = sugargame.canvas.PygameCanvas( self, main=self.game.run, modules=[pygame.display]) # Note that set_canvas implicitly calls read_file when # resuming from the Journal. self.set_canvas(self._pygamecanvas) self._pygamecanvas.grab_focus()
def test_change_number(self): puzzle = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] game = Sudoku(puzzle) for i in range(9): for j in range(9): if game.locked_numbers[i][j]: self.asserter.assertFalse( game.change_number(i, j, 1), msg='change a locked number succeeded') self.asserter.assertEquals(game.puzzle[i][j], puzzle[i][j]) else: self.asserter.assertTrue(game.change_number(i, j, i), msg="initial check failed") self.asserter.assertEquals(game.puzzle[i][j], i) self.asserter.assertTrue(game.change_number(i, j, 0), msg="initial check failed") self.asserter.assertEquals(game.puzzle[i][j], puzzle[i][j])
def solve(sudoku): sudoku = Sudoku(sudoku=sudoku) solved = sudoku.solve() if solved: sudoku_solution = sudoku.solution divider = ' '.join('-' for i in range(len(sudoku_solution))) print('The sudoku has been solved:') print(divider) # print(Sudoku.format(sudoku_solution)) # noinspection PyUnusedLocal print(divider) solution = np.zeros((9, 9)) for i in range(9): for j in range(9): solution[i][j] = int(sudoku_solution[i][j][0]) print(solution) return solution else: print('Failed to solve !!!') return None
def mouseClick(self, mpos): catch = self.mainMenu.findButton(mpos) if (catch == 20): catch = Sudoku.Sudoku(self.screen) if (catch == 13): self.drawWindow() elif (catch == 25): return catch else: pass elif (catch == 21): print(catch) return None elif (catch == 22): print(catch) return None elif (catch == 23): print(catch) return None elif (catch == 24): print(catch) return None else: return catch
def hardlevel(): # win4=GraphWin("Hard Sudoku",600,600) game = Sudoku("hard")
def mediumlevel(): # win3=GraphWin("Medium Sudoku",600,600) game = Sudoku("medium")
def easylevel(): # win2=GraphWin("Easy Sudoku",600,600) game = Sudoku("easy")
clue = False remove = False level = 2 elif event.key == K_F3: menu = False rules = False how_to = False form = False play = True warning = False clue = False remove = False level = 3 grid = Grid(level, size, 480, 480, grid_empty[level - 1]) sudoku = Sudoku(grid) error_counter = 0 # Boucle jeu while play: end = False for event in pygame.event.get(): # Attente des événements if event.type == QUIT or (event.type == KEYDOWN and event.key == K_a): menu = False rules = False how_to = False form = False play = False warning = False clue = False
def main(): sudoku = Sudoku() window = Window("SudokuSolver", SUDOCANVASSIZE, sudoku)
# Artificial Intelligence offered by Columbia University # through edX ######################################################### from Sudoku import * import time with open('sudokus_start.txt') as temp_file: sudokus_start = [line.rstrip('\r\n') for line in temp_file] with open('sudokus_finish.txt') as temp_file: sudokus_finish = [line.rstrip('\r\n') for line in temp_file] N = len(sudokus_start) for k in xrange(N): sudoku = Sudoku(sudokus_start[k]) csp = SudokuCSP(sudoku) AC3(csp) x = BacktrackingSearch(csp) for var in x: csp.domain[var] = [x[var]] sol = "" for row in "ABCDEFGHI": for col in "123456789": sol += str(csp.domain[row + col][0]) print (k + 1, sol == sudokus_finish[k]) time.sleep(0.001)
def __init__(self, parent): # need a frame/container for the 3x3 grid of Entry widgets # need another frame/container for the buttons at the bottom. self.playingGrid = Frame(parent) self.playingGrid.grid(column=1, row=1, sticky=(N, W, E, S)) self.playingGrid['borderwidth'] = 2 self.playingGrid['relief'] = 'sunken' self.buttonRow = Frame(parent) self.buttonRow.grid(column=1, row=2) #--------------playingGrid initialization------------- ''' The grid-index association 0 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 ''' self.topLeft = Frame(self.playingGrid, borderwidth=2, relief='ridge') self.topCenter = Frame(self.playingGrid, borderwidth=2, relief='ridge') self.topRight = Frame(self.playingGrid, borderwidth=2, relief='ridge') self.midLeft = Frame(self.playingGrid, borderwidth=2, relief='ridge') self.midCenter = Frame(self.playingGrid, borderwidth=2, relief='ridge') self.midRight = Frame(self.playingGrid, borderwidth=2, relief='ridge') self.botLeft = Frame(self.playingGrid, borderwidth=2, relief='ridge') self.botCenter = Frame(self.playingGrid, borderwidth=2, relief='ridge') self.botRight = Frame(self.playingGrid, borderwidth=2, relief='ridge') self.topLeft.grid(column=1, row=1) self.topCenter.grid(column=2, row=1) self.topRight.grid(column=3, row=1) self.midLeft.grid(column=1, row=2) self.midCenter.grid(column=2, row=2) self.midRight.grid(column=3, row=2) self.botLeft.grid(column=1, row=3) self.botCenter.grid(column=2, row=3) self.botRight.grid(column=3, row=3) self.entryValues = [] for i in range(81): self.entryValues.append(StringVar()) self.entryList = [] for i in range(81): r = i % 9 if i < 27: if r == 0 or r == 1 or r == 2: print(str(i) + '\t' + str(len(self.entryValues))) self.entryList.append( Entry(self.topLeft, width=3, textvariable=self.entryValues[i])) self.entryList[i].grid(column=(r + 1), row=((i // 9) + 1)) if r == 3 or r == 4 or r == 5: self.entryList.append( Entry(self.topCenter, width=3, textvariable=self.entryValues[i])) self.entryList[i].grid(column=(r + 1), row=((i // 9) + 1)) if r == 6 or r == 7 or r == 8: self.entryList.append( Entry(self.topRight, width=3, textvariable=self.entryValues[i])) self.entryList[i].grid(column=(r + 1), row=((i // 9) + 1)) elif i < 54: if r == 0 or r == 1 or r == 2: self.entryList.append( Entry(self.midLeft, width=3, textvariable=self.entryValues[i])) self.entryList[i].grid(column=(r + 1), row=((i // 9) + 1)) if r == 3 or r == 4 or r == 5: self.entryList.append( Entry(self.midCenter, width=3, textvariable=self.entryValues[i])) self.entryList[i].grid(column=(r + 1), row=((i // 9) + 1)) if r == 6 or r == 7 or r == 8: self.entryList.append( Entry(self.midRight, width=3, textvariable=self.entryValues[i])) self.entryList[i].grid(column=(r + 1), row=((i // 9) + 1)) else: if r == 0 or r == 1 or r == 2: self.entryList.append( Entry(self.botLeft, width=3, textvariable=self.entryValues[i])) self.entryList[i].grid(column=(r + 1), row=((i // 9) + 1)) if r == 3 or r == 4 or r == 5: self.entryList.append( Entry(self.botCenter, width=3, textvariable=self.entryValues[i])) self.entryList[i].grid(column=(r + 1), row=((i // 9) + 1)) if r == 6 or r == 7 or r == 8: self.entryList.append( Entry(self.botRight, width=3, textvariable=self.entryValues[i])) self.entryList[i].grid(column=(r + 1), row=((i // 9) + 1)) #--------------buttonRow initialization--------------- self.loadGame = Button(self.buttonRow, text='load', command=self.openPuzzle) self.saveGame = Button(self.buttonRow, text='save') self.checkGame = Button(self.buttonRow, text='check', command=self.check) self.loadGame.grid(column=1, row=1) self.saveGame.grid(column=2, row=1) self.checkGame.grid(column=3, row=1) #--------------initializing the puzzle---------------- self.puzzle = Sudoku() self.updateGrid()
break size = int(input('Rozmiar tablicy: ')) print('1: Backtracking, 2: Forward Checking') algorithm_id = int(input('Algorytm: ')) algorithm = var_h = val_h = None if algorithm_id == 1: algorithm = 'BT' elif algorithm_id == 2: algorithm = 'FC' print( '0: FIRST,1: MEDIUM, 2: MOST_CONSTRAINED, 3: LESS CONSTRAINED') var_h = int(input('Heurystyka wyboru zmiennej: ')) val_h = int(input('Heurystyka wyboru wartości: ')) else: pass print('Working...') if problem == 1: CSP = NQueens(size) elif problem == 2: CSP = LatinSquare(size) elif problem == 3: CSP = Sudoku(size) start = time.time() solution, success = solve(CSP, algorithm, var_h, val_h) end = time.time() print('Time: ', end - start) solution.print_solution() # cProfile.run('solve(NQueens(size), algorithm, var_h, val_h)')