2019-11-30 13:55:22 +01:00
|
|
|
#!/usr/bin/python3
|
|
|
|
|
|
|
|
"""This is a Sudoku Solver."""
|
|
|
|
|
2020-01-24 16:51:25 +01:00
|
|
|
import argparse
|
2019-11-30 13:55:22 +01:00
|
|
|
from board import Board
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
2019-11-30 17:04:43 +01:00
|
|
|
"""Provided a string representing a Sudoku game, solve it."""
|
|
|
|
|
2020-01-24 16:51:25 +01:00
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser.add_argument('file', help='file containing the Sudoku to solve')
|
|
|
|
args = parser.parse_args()
|
|
|
|
sudoku_file = args.file
|
2019-12-01 19:27:38 +01:00
|
|
|
|
2020-01-24 16:51:25 +01:00
|
|
|
strings = find_strings_in(sudoku_file)
|
|
|
|
|
|
|
|
# default string if file wasn't computed
|
|
|
|
if len(strings) == 0:
|
|
|
|
strings = [(
|
|
|
|
".....6...\n"
|
|
|
|
"..2.35.8.\n"
|
|
|
|
"....2..13\n"
|
|
|
|
".2....19.\n"
|
|
|
|
"93....7..\n"
|
|
|
|
"5....4...\n"
|
|
|
|
"1......7.\n"
|
|
|
|
".7...142.\n"
|
|
|
|
".9.4.3...\n"
|
|
|
|
)]
|
|
|
|
|
|
|
|
for string in strings:
|
|
|
|
solve_board(string, debug=False)
|
|
|
|
|
|
|
|
|
|
|
|
def find_strings_in(sudoku_file: str) -> list:
|
|
|
|
"""Extract the Sudoku string from a file.
|
|
|
|
|
|
|
|
Return a list of the Sudoku strings.
|
|
|
|
"""
|
|
|
|
|
|
|
|
strings: list = []
|
|
|
|
|
|
|
|
try:
|
|
|
|
with open(sudoku_file, 'r') as sudokus:
|
|
|
|
string = ""
|
|
|
|
for line in sudokus.readlines():
|
|
|
|
if len(line) == 10:
|
|
|
|
string += line
|
|
|
|
elif len(line) == 1:
|
|
|
|
strings.append(string)
|
|
|
|
string = ""
|
|
|
|
else:
|
|
|
|
raise AssertionError("Invalid file")
|
|
|
|
|
|
|
|
except FileNotFoundError:
|
|
|
|
print("File not found, using default string.")
|
|
|
|
|
|
|
|
return strings
|
2019-11-30 17:52:45 +01:00
|
|
|
|
2019-11-30 13:55:22 +01:00
|
|
|
|
2019-12-03 16:02:24 +01:00
|
|
|
def solve_board(string: str, debug=False):
|
|
|
|
"""This function loops over the iteration process."""
|
2019-11-30 13:55:22 +01:00
|
|
|
|
2019-12-02 15:21:49 +01:00
|
|
|
board = Board(string, debug=debug)
|
2020-01-24 16:51:25 +01:00
|
|
|
print(board)
|
|
|
|
input("Hit ENTER to solve")
|
2019-12-03 12:00:32 +01:00
|
|
|
iterations = 0
|
|
|
|
while '.' in string:
|
|
|
|
iterations += 1
|
|
|
|
print(board)
|
|
|
|
board.compute_possible_values()
|
2019-12-03 16:02:24 +01:00
|
|
|
board.compute_obligated_values()
|
|
|
|
string = board.update_string()
|
2019-12-03 12:00:32 +01:00
|
|
|
board.update_board()
|
2019-12-03 16:02:24 +01:00
|
|
|
print(board)
|
|
|
|
|
|
|
|
print(f"Solved in {iterations} iterations.")
|
2020-01-24 16:51:25 +01:00
|
|
|
input("Hit ENTER to continue")
|
2019-11-30 15:21:33 +01:00
|
|
|
|
2019-11-30 13:55:22 +01:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|
2020-01-24 16:51:25 +01:00
|
|
|
|