MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / random_puzzle

Function random_puzzle

data_structures/arrays/sudoku_solver.py:213–226  ·  view source on GitHub ↗

Make a random puzzle with N or more assignments. Restart on contradictions. Note the resulting puzzle is not guaranteed to be solvable, but empirically about 99.8% of them are solvable. Some have multiple solutions.

(assignments=17)

Source from the content-addressed store, hash-verified

211
212
213def random_puzzle(assignments=17):
214 """
215 Make a random puzzle with N or more assignments. Restart on contradictions.
216 Note the resulting puzzle is not guaranteed to be solvable, but empirically
217 about 99.8% of them are solvable. Some have multiple solutions.
218 """
219 values = dict.fromkeys(squares, digits)
220 for s in shuffled(squares):
221 if not assign(values, s, random.choice(values[s])):
222 break
223 ds = [values[s] for s in squares if len(values[s]) == 1]
224 if len(ds) >= assignments and len(set(ds)) >= 8:
225 return "".join(values[s] if len(values[s]) == 1 else "." for s in squares)
226 return random_puzzle(assignments) ## Give up and make a new puzzle
227
228
229def shuffled(seq):

Callers 1

sudoku_solver.pyFile · 0.85

Calls 2

shuffledFunction · 0.85
assignFunction · 0.85

Tested by

no test coverage detected