def naiive_backtrack(board_code): """Naiive backtracking algorithm used to find the solution to a board with missing clues. Parameters ---------- board_code : string Board code listed from top left to bottom right. Returns ------- string Board code for solved board. Raises ------ UnsolvableBoardException If the board does not have a solution. InvalidBoardException If the board code is invalid. """ board = util.code_to_board(board_code) if not util.board_is_valid(board): raise util.InvalidBoardException search_board = np.copy(board) if util.board_is_solved(board): return util.board_to_code(board) position = 0 step = 0 while True: step += 1 if position == 81: if not util.board_is_solved(search_board): raise util.InvalidBoardException # if we got here when solving there must have been an issue with the board code print(f'Solved board in {step} steps') return util.board_to_code(search_board) x = util.to_x(position) y = util.to_y(position) if board[x][y] != 0: position += 1 continue while search_board[x][y] <= 9: search_board[x][y] += 1 if util.position_is_valid(search_board, x, y): position += 1 break if search_board[x][y] == 10: search_board[x][y] = 0 position -= 1 if position < 0: raise util.UnsolvableBoardException while board[util.to_x(position)][util.to_y(position)] != 0: position -= 1 if position < 0: raise util.UnsolvableBoardException
def naiive_backtrack_count(board_code): """Naiive backtracking algorithm used to count solutions to a board with missing clues. Parameters ---------- board_code : string Board code listed from top left to bottom right. Returns ------- int The number of unique solutions the board has. """ board = util.code_to_board(board_code) search_board = np.copy(board) if util.board_is_solved(board): return 1 position = 0 step = 0 solutions = 0 while True: step += 1 if position == 81: if not util.board_is_solved(search_board): raise util.InvalidBoardException solutions += 1 position -= 1 while board[util.to_x(position)][util.to_y(position)] != 0: position -= 1 if position < 0: print(f'found {solutions} solutions in {step} steps') return solutions x = util.to_x(position) y = util.to_y(position) if board[x][y] != 0: position += 1 continue while search_board[x][y] <= 9: search_board[x][y] += 1 if util.position_is_valid(search_board, x, y): position += 1 break if search_board[x][y] == 10: search_board[x][y] = 0 position -= 1 if position < 0: print(f'found {solutions} solutions in {step} steps') return solutions while board[util.to_x(position)][util.to_y(position)] != 0: position -= 1 if position < 0: print(f'found {solutions} solutions in {step} steps') return solutions
def test_board_is_solved(): board = util.code_to_board(boards['81'][0]) board[0][0] = -1 with pytest.raises(util.InvalidBoardException): util.board_is_solved(board) board = util.code_to_board(boards['24'][0]) assert not util.board_is_solved(board) board = util.code_to_board(boards['81'][0]) assert util.board_is_solved(board)
def test_unique_recursive(board, guesses): if len(guesses) == 0: if util.board_is_solved(board): return 1 else: return 0 solutions = 0 minimum_guesses = guesses.pop(0) for tentative in minimum_guesses['guesses']: # for each guess in the minimum guess cell, try it and see if it leads to a solution board[minimum_guesses['x']][minimum_guesses['y']] = tentative updated_guesses = [] # to update guesses, iterate over all of the old guesses and see if they have to be changed after inserting the new tentative guess for old_guess in guesses: new_guess = {'x': old_guess['x'], 'y': old_guess['y'], 'guesses': old_guess['guesses'][:]} # creating a deep copy of the guess if tentative in new_guess['guesses']: if new_guess['x'] == minimum_guesses['x'] or new_guess['y'] == minimum_guesses['y'] or (new_guess['x'] // 3 == minimum_guesses['x'] // 3 and new_guess['y'] // 3 == minimum_guesses['y'] // 3): new_guess['guesses'].remove(tentative) # forward checking if len(new_guess['guesses']) == 0: return 0 updated_guesses.append(new_guess) updated_guesses = sorted(updated_guesses, key=lambda guess: len(guess['guesses'])) next_step = test_unique_recursive(board, updated_guesses) solutions += next_step return solutions
def test_all_boards(): boards = load('tests/test-boards.json') for guess_count in sorted(list(boards.keys()), reverse=True): if guess_count == '81': continue print(guess_count) for index in range(len(boards[guess_count])): code = boards[guess_count][index] # print(code) board = code_to_board(code) guess_board = init_guesses(board) modified = True i = 0 while modified: i += 1 modified = False for move_type in deductive_methods: result, _, _ = deductive_methods[move_type][0](guess_board) if result: # print(i, move_type) modified = True break if not util.board_is_solved(util.remove_guesses(guess_board)): print(code) exit()
def test_dfs(n=50): # testing solved board code = sudokus['81'][0] solution = dfs.dfs(code) assert util.board_is_solved(util.code_to_board(solution)) # testing unsolveable board code = sudokus['81'][0] code = '77' + code[2:] with pytest.raises(util.UnsolvableBoardException): solution = dfs.dfs(code) import random for i in tqdm(range(n)): code = test_list.pop(np.random.randint(0, len(test_list))) solution = dfs.dfs(code) assert util.board_is_solved(util.code_to_board(solution)) print(f'dfs solved {n} boards')
def test_backtrack(n=1): # testing solved board code = sudokus['81'][0] solution = backtracking.naiive_backtrack(code) assert util.board_is_solved(util.code_to_board(solution)) # testing unsolveable board code = sudokus['81'][0] code = '77' + code[2:] with pytest.raises(util.InvalidBoardException): solution = backtracking.naiive_backtrack(code) import random for i in tqdm(range(n)): code = test_list.pop(np.random.randint(0, len(test_list))) solution = backtracking.naiive_backtrack(code) assert util.board_is_solved(util.code_to_board(solution)) print(f'naiive backtrack solved {n} boards')
def fill_board(): code = '0' * 81 board = util.code_to_board(code) guesses = util.generate_guess_list(board) np.random.shuffle(guesses) for cell in guesses: np.random.shuffle(cell['guesses']) # print(guesses) pbar = tqdm(total=81) while (len(guesses)): pbar.update(1) # while there are empty cells random_cell = guesses.pop(0) for tentative in random_cell['guesses']: forward_valid = True # for each guess in the cell, try it and see if it leads to a solution board[random_cell['x']][random_cell['y']] = tentative updated_guesses = [] # to update guesses, iterate over all of the old guesses and see if they have to be changed after inserting the new tentative guess for old_guess in guesses: new_guess = { 'x': old_guess['x'], 'y': old_guess['y'], 'guesses': old_guess['guesses'][:] } # creating a deep copy of the guess if tentative in new_guess['guesses']: if new_guess['x'] == random_cell['x'] or new_guess[ 'y'] == random_cell['y'] or ( new_guess['x'] // 3 == random_cell['x'] // 3 and new_guess['y'] // 3 == random_cell['y'] // 3): new_guess['guesses'].remove(tentative) # forward checking if len(new_guess['guesses']) == 0: forward_valid = False break updated_guesses.append(new_guess) if forward_valid: try: solution = dfs.dfs_from_board(np.copy(board)) guesses = updated_guesses break # break out of this tentative testing loop except util.UnsolvableBoardException: board[random_cell['x']][random_cell['y']] = 0 else: board[random_cell['x']][random_cell['y']] = 0 pbar.close() assert util.board_is_solved(board) return board
def dfs(board_code): """Depth first search of board solutions, selecting branches with fewest possible guesses. Parameters ---------- board_code : string Board code listed from top left to bottom right. Returns ------- string Board code for solved board. Raises ------ UnsolvableBoardException If the board does not have a solution. """ board = util.code_to_board(board_code) if util.board_is_solved(board): return util.board_to_code(board) return dfs_from_board(board)