In [ ]:
%%HTML
<style>
.container { width:100% }
</style>

Sudoku

The sudoku we want to solve is shown below:

This sudoku can be represented by the following list of lists:


In [ ]:
Sudoku = [ ["*",  3 ,  9 , "*", "*", "*", "*", "*",  7 ], 
           ["*", "*", "*",  7 , "*", "*",  4 ,  9 ,  2 ],
           ["*", "*", "*", "*",  6 ,  5 , "*",  8 ,  3 ],
           ["*", "*", "*",  6 , "*",  3 ,  2 ,  7 , "*"],
           ["*", "*", "*", "*",  4 , "*",  8 , "*", "*"],
           [ 5 ,  6 , "*", "*", "*", "*", "*", "*", "*"],
           ["*", "*",  5 ,  2 , "*",  9 , "*", "*",  1 ],
           ["*",  2 ,  1 , "*", "*", "*", "*",  4 , "*"],
           [ 7 , "*", "*", "*", "*", "*",  5 , "*", "*"]
         ]

The function sudoku_csp returns a CSP that encodes the given sudoku as a CSP. The variables should have names like $\texttt{V}ij$ where $i,j \in \{1,\cdots,9\}$. For example, V21 would be the variable describing the first cell in the second row.


In [ ]:
def sudoku_csp(Puzzle): 
    "your code here"

In [ ]:
sudoku_csp(Sudoku)

In [ ]:
import ipycanvas as cnv

In [ ]:
size = 100

The function show_solution prints the solution.


In [ ]:
def show_solution(Solution):
    canvas = cnv.Canvas(size=(size * 9, size * 9))
    canvas.font = '20px sans-serif'
    canvas.text_align    = 'center'
    canvas.text_baseline = 'middle'
    for row in range(9):
        for col in range(9):
            x = col * size
            y = row * size
            canvas.line_width = 1.0
            canvas.stroke_rect(x, y, size, size)
            entry = Sudoku[row][col]
            if entry == '*':
                key = f'V{row+1}{col+1}'
                symbol = str(Solution[key])
                canvas.fill_style = 'blue'
            else:
                symbol = str(entry)
                canvas.fill_style = 'black'
            x += size // 2
            y += size // 2
            canvas.fill_text(symbol, x, y)
    canvas.line_width = 3.0
    for row in range(3):
        for col in range(3):
            x = 3 * col * size
            y = 3 * row * size
            canvas.stroke_rect(x, y, 3 * size, 3 * size)
    canvas.stroke_style = 'black'
    canvas.line_width = 6.0
    canvas.stroke_rect(0, 0, 9 * size, 9 * size) 
    display(canvas)