So I am trying to solve a problem which makes you compare numbers in the 9x9 sudoku grid so see if the game of Sudoku has a valid/solvable grid of numbers (Meaning that the rules of Sudoku apply to the given grid). I have pretty much solved the problem, but I am stuck on this last part. I have figured out how sum up each element on each column/row, but I am not able to completely solve this problem until I can actually check each 3x3 grid to see if there are no duplicate numbers in them. This is where I am stuck because I cannot seem to get the right algorithm to iterate through the matrix in a 3x3 fashion.
I tried to control the iteration completely by using a series of for loops that increase the certain index number so it moves along the matrix. Let me know what I am doing wrong--or if there are any other possible, more elegant ways to solve this problem (using so many for loops makes my code look long and ugly/less efficient).
def sudoku(grid):
grid = [[1,3,2,5,4,6,9,8,7],
[4,6,5,8,7,9,3,2,1],
[7,9,8,2,1,3,6,5,4],
[9,2,1,4,3,5,8,7,6],
[3,5,4,7,6,8,2,1,9],
[6,8,7,1,9,2,5,4,3],
[5,7,6,9,8,1,4,3,2],
[2,4,3,6,5,7,1,9,8],
[8,1,9,3,2,4,7,6,5]]
duplicate = set()
numHolder = 0
for a in range(0,9):
for b in range(0,9):
numHolder+=grid[b][a]
if numHolder!=45:
return False
numHolder=0
for b in range(0,9):
for x in range(0, 9):
numHolder += grid[b][x]
if numHolder != 45:
return False
numHolder = 0
for b in range(0,3):
for c in range(0,3):
if grid[b][c] in duplicate:
return False
else:
duplicate.add(grid[b][c])
duplicate.clear()
for d in range(0,3):
for e in range(0,3):
if grid[d][c+3] in duplicate:
return False
else:
duplicate.add(grid[d][c+3])
duplicate.clear()
for d in range(0,3):
for e in range(0,3):
if grid[b][c+6] in duplicate:
return False
else:
duplicate.add(grid[d][c+6])
duplicate.clear()
for d in range(0,3):
for e in range(0,3):
if grid[d+3][c] in duplicate:
return False
else:
duplicate.add(grid[d+3][c])
duplicate.clear()
for d in range(0,3):
for e in range(0,3):
if grid[d+3][c+3] in duplicate:
return False
else:
duplicate.add(grid[d+3][c+3])
duplicate.clear()
for d in range(0,3):
for e in range(0,3):
if grid[d+3][c+6] in duplicate:
return False
else:
duplicate.add(grid[d+3][c+6])
duplicate.clear()
for d in range(0,3):
for e in range(0,3):
if grid[d+6][c] in duplicate:
return False
else:
duplicate.add(grid[d+6][c])
duplicate.clear()
for d in range(0,3):
for e in range(0,3):
if grid[d+6][c+3] in duplicate:
return False
else:
duplicate.add(grid[d+6][c+3])
duplicate.clear()
for d in range(0,3):
for e in range(0,3):
if grid[d+6][c+6] in duplicate:
return False
else:
duplicate.add(grid[d+6][c+6])
return True