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)
| 211 | |
| 212 | |
| 213 | def 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 | |
| 229 | def shuffled(seq): |
no test coverage detected