Last active
March 4, 2020 08:34
-
-
Save shiracamus/2f4cc861bec3b621e98c0cab26d27411 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import numpy as np | |
_ = 0 | |
problem = [ | |
[_, _, _, _, 4, _, _, _, _], | |
[_, _, 5, _, _, _, _, _, _], | |
[_, 3, 6, 8, _, _, _, 7, 2], | |
[_, 8, _, _, _, 6, 5, _, _], | |
[1, _, _, 5, _, _, _, 9, _], | |
[_, _, _, _, _, _, 2, _, 7], | |
[_, 1, _, 2, _, 8, 4, 3, 6], | |
[_, _, 8, _, _, 4, 7, _, 9], | |
[_, 6, _, _, 1, _, _, _, 5], | |
] | |
answer = np.zeros((9, 9)) | |
candidates = np.ones((9, 9, 9)) | |
def fixed(y, x, number): | |
answer[y, x] = number | |
candidates[y, x] = 0 | |
candidates[y, :, number-1] = 0 | |
candidates[:, x, number-1] = 0 | |
candidates[y//3*3:y//3*3+3, x//3*3:x//3*3+3, number-1] = 0 | |
for y, row in enumerate(problem): | |
for x, number in enumerate(row): | |
if number != 0: | |
fixed(y, x, number) | |
while np.any(answer == 0): | |
for y, row in enumerate(candidates): | |
for x, candidate in enumerate(row): | |
if answer[y, x] != 0: | |
continue | |
if candidate.sum() == 1: | |
fixed(y, x, np.where(candidate == 1)[0] + 1) | |
continue | |
for i in range(9): | |
if candidate[i] == 0: | |
continue | |
if (candidates[y, :, i].sum() == 1 | |
or candidates[:, x, i].sum() == 1 | |
or candidates[y//3*3:y//3*3+3, x//3*3:x//3*3+3, i].sum() == 1): | |
fixed(y, x, i + 1) | |
print("-------------------") | |
print(*answer, sep="\n") | |
print("-------------------") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment