Skip to content

Instantly share code, notes, and snippets.

@quietcricket
Created May 11, 2018 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quietcricket/9fa2d5c9cf5ea34dbede40e69b0d5aa4 to your computer and use it in GitHub Desktop.
Save quietcricket/9fa2d5c9cf5ea34dbede40e69b0d5aa4 to your computer and use it in GitHub Desktop.
Algorithm to check if a sudoku solution is valid
from __future__ import print_function, division
def check_sudoku(arr):
# 9 rows, 9 columns and 9 sub squares
# Each of them need to have all the digits
# Not using bit shifting
alignments = [987654321] * 27
for i, row in enumerate(arr):
for j, x in enumerate(row):
if x == 0:
return False
n = x * pow(10, x - 1)
alignments[i] -= n
alignments[9 + j] -= n
alignments[18 + i // 3 * 3 + j // 3] -= n
return sum(alignments) == 0
test_arr = [[5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 5, 3, 4, 8], [1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3], [4, 2, 6, 8, 5,
3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5], [3, 4, 5, 2, 8, 6, 1, 7, 9]]
check_sudoku(test_arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment