Create a sudoku solution CHECKER

Python, 103

I hate sudoku.

b = [[1,2,3,4,5,6,7,8,9],
     [4,5,6,7,8,9,1,2,3],
     [7,8,9,1,2,3,4,5,6],
     [2,3,1,5,6,4,8,9,7],
     [5,6,4,8,9,7,2,3,1],
     [8,9,7,2,3,1,5,6,4],
     [3,1,2,6,4,5,9,7,8],
     [6,4,5,9,7,8,3,1,2],
     [9,7,8,3,1,2,6,4,5]]

e=enumerate;print 243-len(set((a,t)for(i,r)in e(b)for(j,t)in e(r)for a in e([i,j,i/3*3+j/3]*(0<t<10))))

How it works: each row, column, and block must have each number from 1 to 9. So for each 0 <= i, j < 9, the cell i,j is in block 3*floor(i/3) + floor(j/3). Thus, there are 243 requirements to satisfy. I make each requirement a tuple ((item index,item type number),symbol) where item index is a number between 0 and 8 (inclusive), item type number is 0,1, or 2 to denote row, column or block respectively, and symbol is the entry b[i][j].

Edit: I mistakenly didn't check for valid entries. Now I do.


APL (46)

{∧/,↑∊∘Z¨(/∘(,⍵)¨↓Z∘.=,3/3⌿3 3⍴Z←⍳9),(↓⍵),↓⍉⍵}

This takes a 9-by-9 matrix. The example one can be entered on TryAPL like so:

     sudoku ← ↑(1 2 3 4 5 6 7 8 9)(4 5 6 7 8 9 1 2 3)(7 8 9 1 2 3 4 5 6)(2 3 1 5 6 4 8 9 7)(5 6 4 8 9 7 2 3 1)(8 9 7 2 3 1 5 6 4)(3 1 2 6 4 5 9 7 8)(6 4 5 9 7 8 3 1 2)(9 7 8 3 1 2 6 4 5)
     {∧/,↑∊∘Z¨(/∘(,⍵)¨↓Z∘.=,3/3⌿3 3⍴Z←⍳9),(↓⍵),↓⍉⍵} sudoku
1

Explanation:

  • ↓⍉⍵: get the columns of ,
  • ↓⍵: get the rows of ,
  • 3/3⌿3 3⍴Z←⍳9: make a 3-by-3 matrix containing the numbers 1 to 9, then triplicate each number in both directions, giving a 9-by-9 matrix with the numbers 1 to 9 indicating each group,
  • Z∘.=: for each number 1 to 9, make a bitmask for the given group,
  • /∘(,⍵)¨: and mask with each, giving the groups of .
  • ∊∘Z¨: for each sub-array, see if it contains the numbers 1 to 9,
  • ∧/,↑: take the logical and of all of these numbers together.

GolfScript, 39 characters

.zip.{3/}%zip{~}%3/{[]*}%++{$10,1>=!},,

It takes an array of arrays as input (see online example) and outputs 0 if it is a valid grid.

Short explanation of the code

.zip         # Copy the input array and transpose it
.{3/}%       # Split each line into 3 blocks
zip{~}%      # Transpose these blocks
3/{[]*}%     # Do the same for the lines themselves and join again
++           # Make one large list of 27 9-element arrays 
             # (9 for rows, 9 for columns, 9 for blocks)
{$10,1>=!},  # From those 27 select the ones which are not a permutation of [1 2 3 ... 9]
             #   $      -> sort
             #   10,1>  -> [1 2 3 ... 9]
             #   =!     -> not equal
,            # Count after filtering