-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: solve sudoku puzzle #1
Open
MrHeer
wants to merge
1
commit into
main
Choose a base branch
from
feat/sudoku
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
import random | ||
|
||
"ref: [Solving Every Sudoku Puzzle](https://norvig.com/sudoku.html)" | ||
|
||
|
||
def cross(A: str, B: str): | ||
"Cross product of elements in A and elements in B." | ||
return [a+b for a in A for b in B] | ||
|
||
|
||
digits = '123456789' | ||
rows = 'ABCDEFGHI' | ||
cols = digits | ||
squares = cross(rows, cols) | ||
unit_list = ([cross(rows, c) for c in cols] + | ||
[cross(r, cols) for r in rows] + | ||
[cross(rs, cs) for rs in ('ABC', 'DEF', 'GHI') for cs in ('123', '456', '789')]) | ||
units = dict((s, [u for u in unit_list if s in u]) | ||
for s in squares) | ||
peers = dict((s, set(sum(units[s], []))-set([s])) | ||
for s in squares) | ||
|
||
|
||
def assign(values, s, d): | ||
"""Eliminate all the other values (except d) from values[s] and propagate. | ||
Return values, except return False if a contradiction is detected.""" | ||
other_values = values[s].replace(d, '') | ||
if all(eliminate(values, s, d2) for d2 in other_values): | ||
return values | ||
else: | ||
return False | ||
|
||
|
||
def eliminate(values, s, d): | ||
"""Eliminate d from values[s]; propagate when values or places <= 2. | ||
Return values, except return False if a contradiction is detected.""" | ||
if d not in values[s]: | ||
return values # Already eliminated | ||
values[s] = values[s].replace(d, '') | ||
# (1) If a square s is reduced to one value d2, then eliminate d2 from the peers. | ||
if len(values[s]) == 0: | ||
return False # Contradiction: removed last value | ||
elif len(values[s]) == 1: | ||
d2 = values[s] | ||
if not all(eliminate(values, s2, d2) for s2 in peers[s]): | ||
return False | ||
# (2) If a unit u is reduced to only one place for a value d, then put it there. | ||
for u in units[s]: | ||
dplaces = [s for s in u if d in values[s]] | ||
if len(dplaces) == 0: | ||
return False # Contradiction: no place for this value | ||
elif len(dplaces) == 1: | ||
# d can only be in one place in unit; assign it there | ||
if not assign(values, dplaces[0], d): | ||
return False | ||
return values | ||
|
||
|
||
def solve(values): return search(values) | ||
|
||
|
||
def search(values): | ||
"Using depth-first search and propagation, try all possible values." | ||
if values is False: | ||
return False # Failed earlier | ||
if all(len(values[s]) == 1 for s in squares): | ||
return values # Solved! | ||
# Chose the unfilled square s with the fewest possibilities | ||
n, s = min((len(values[s]), s) for s in squares if len(values[s]) > 1) | ||
return some(search(assign(values.copy(), s, d)) | ||
for d in values[s]) | ||
|
||
|
||
def some(seq): | ||
"Return some element of seq that is true." | ||
for e in seq: | ||
if e: | ||
return e | ||
return False | ||
|
||
|
||
def solved(values): | ||
"A puzzle is solved if each unit is a permutation of the digits 1 to 9." | ||
def unit_solved(unit): return set(values[s] for s in unit) == set(digits) | ||
return values is not False and all(unit_solved(unit) for unit in unit_list) | ||
|
||
|
||
def random_puzzle(N=17): | ||
"""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.""" | ||
values = dict((s, digits) for s in squares) | ||
for s in shuffled(squares): | ||
if not assign(values, s, random.choice(values[s])): | ||
break | ||
ds = [values[s] for s in squares if len(values[s]) == 1] | ||
if len(ds) >= N and len(set(ds)) >= 8: | ||
return values | ||
return random_puzzle(N) # Give up and make a new puzzle | ||
|
||
|
||
def shuffled(seq): | ||
"Return a randomly shuffled copy of the input sequence." | ||
seq = list(seq) | ||
random.shuffle(seq) | ||
return seq | ||
|
||
|
||
def generate_puzzle(N=17): | ||
puzzle = random_puzzle(N) | ||
while (solved(solve(puzzle)) == False): | ||
puzzle = random_puzzle(N) | ||
return puzzle |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这是一个重复计算的值?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
什么叫重复计算的值?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
应该是一个常量,只要计算一次即可。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
不知道你在说什么