-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
84 lines (71 loc) · 2.71 KB
/
main.py
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
81
82
83
84
from csp_representation import CSP
from csp_solver import *
def create_map_coloring_csp():
"""Instantiate a CSP representing the map coloring problem from the
textbook. This can be useful for testing your CSP solver as you
develop your code.
"""
csp = CSP()
states = [ 'WA', 'NT', 'Q', 'NSW', 'V', 'SA', 'T' ]
edges = { 'SA': [ 'WA', 'NT', 'Q', 'NSW', 'V' ], 'NT': [ 'WA', 'Q' ], 'NSW': [ 'Q', 'V' ] }
colors = [ 'red', 'green', 'blue' ]
for state in states:
csp.add_variable(state, colors)
for state, other_states in edges.items():
for other_state in other_states:
csp.add_constraint_one_way(state, other_state, lambda i, j: i != j)
csp.add_constraint_one_way(other_state, state, lambda i, j: i != j)
return csp
def create_sudoku_csp(filename):
"""Instantiate a CSP representing the Sudoku board found in the text
file named 'filename' in the current directory.
"""
csp = CSP()
path = f"boards/{filename}"
board = open(path, 'r')
board = list(map(lambda x: x.strip("\n"), board))
for row in range(9):
for col in range(9):
if board[row][col] == '0':
csp.add_variable('%d-%d' % (row, col), map(str, range(1, 10)))
else:
csp.add_variable('%d-%d' % (row, col), [ board[row][col] ])
for row in range(9):
csp.add_all_different_constraint([ '%d-%d' % (row, col) for col in range(9) ])
for col in range(9):
csp.add_all_different_constraint([ '%d-%d' % (row, col) for row in range(9) ])
for box_row in range(3):
for box_col in range(3):
cells = []
for row in range(box_row * 3, (box_row + 1) * 3):
for col in range(box_col * 3, (box_col + 1) * 3):
cells.append('%d-%d' % (row, col))
csp.add_all_different_constraint(cells)
return csp
print("Very Hard Board")
sdk_csp = create_sudoku_csp("veryhard.txt")
solution = backtracking_search(sdk_csp)
def print_sudoku_solution(solution):
"""Convert the representation of a Sudoku solution as returned from
the method CSP.backtracking_search(), into a human readable
representation.
"""
counter = 0
counter_two = 0
counter_three = 0
row = ""
for key, value in solution.items():
row += str(value[0]) + " "
counter += 1
counter_two += 1
if counter_two % 3 == 0:
row += "|"
counter_two = 0
if counter % 9 == 0:
counter_three += 1
print(row)
if counter_three % 3 == 0:
counter_three = 0
print("---------------------")
row = ""
print_sudoku_solution(solution)