MCPcopy Index your code
hub / github.com/PySimpleGUI/PySimpleGUI / generate_sudoku

Function generate_sudoku

DemoPrograms/Demo_Sudoku.py:22–50  ·  view source on GitHub ↗

Create a Sukoku board :param mask_rate: % of squares to hide :type mask_rate: float :rtype: List[numpy.ndarry, numpy.ndarry]

(mask_rate)

Source from the content-addressed store, hash-verified

20
21
22def generate_sudoku(mask_rate):
23 """
24 Create a Sukoku board
25
26 :param mask_rate: % of squares to hide
27 :type mask_rate: float
28 :rtype: List[numpy.ndarry, numpy.ndarry]
29 """
30 while True:
31 n = 9
32 solution = np.zeros((n, n), np.int)
33 rg = np.arange(1, n + 1)
34 solution[0, :] = np.random.choice(rg, n, replace=False)
35 try:
36 for r in range(1, n):
37 for c in range(n):
38 col_rest = np.setdiff1d(rg, solution[:r, c])
39 row_rest = np.setdiff1d(rg, solution[r, :c])
40 avb1 = np.intersect1d(col_rest, row_rest)
41 sub_r, sub_c = r//3, c//3
42 avb2 = np.setdiff1d(np.arange(0, n+1), solution[sub_r*3:(sub_r+1)*3, sub_c*3:(sub_c+1)*3].ravel())
43 avb = np.intersect1d(avb1, avb2)
44 solution[r, c] = np.random.choice(avb, size=1)
45 break
46 except ValueError:
47 pass
48 puzzle = solution.copy()
49 puzzle[np.random.choice([True, False], size=solution.shape, p=[mask_rate, 1 - mask_rate])] = 0
50 return puzzle, solution
51
52
53

Callers 1

create_and_show_puzzleFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected