Last active
March 14, 2021 21:26
-
-
Save ideepu/d7af7792fd28660f965089169cadda25 to your computer and use it in GitHub Desktop.
Program which takes a Sodoku puzzle as input and solves it for you. The puzzle has to given as a string combining the row wise and filling the empty values with 0.
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
puzzle = "004006079000000602056092300078061030509000406020540890007410920105000000840600100" | |
def line_to_grid(values): | |
grid = [] | |
for i in range(0,9): | |
grid.append(list(map(lambda x: int(x), list(values[i*9:(i+1)*9])))) | |
return grid | |
def grid_to_line(grid): | |
line = "" | |
line = [line + str(i) for row in grid for i in row] | |
return "".join(line) | |
def small_grid(c, r): | |
for i in range(int(c/3) * 3, (int(c/3) * 3) + 3): | |
for j in range(int(r/3) * 3, (int(r/3) * 3) + 3): | |
if not (i == c and j == r): | |
yield (i,j) | |
def detect_possible(grid, c, r): | |
possible = [1,2,3,4,5,6,7,8,9] | |
# Ignoring if the values is already filled | |
if grid[r][c] is not 0: | |
return False | |
# Removing small grid number from possible combinations | |
for v, k in small_grid(c, r): | |
if grid[k][v] in possible: | |
possible.remove(grid[k][v]) | |
# Removing same row filled values | |
[possible.remove(rv) for rv in grid[r] if rv in possible] | |
# Removing same column filled values | |
[possible.remove(grid[i][c]) for i in range(0,len(grid)) if grid[i][c] in possible] | |
return possible | |
## change the following to recursive method | |
grid = line_to_grid(puzzle) | |
grid_poss = {} | |
while True: | |
count = 0 | |
for i in range(0,9): | |
for j in range(0,9): | |
grid_poss[(i,j)] = detect_possible(grid, r=i, c=j) | |
if not grid_poss[(i,j)]: | |
count += 1 | |
elif len(grid_poss[(i,j)]) == 1: | |
grid[i][j] = grid_poss[(i,j)][0] | |
if count == 81: | |
break | |
grid_to_line(grid) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment