  function Jan23()
% Sudoku checker
clc
A = [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 a correct solution...
alfa = Sudoku(A);
fprintf('Sudoku(A) = %1d\n',alfa)
% This one is ok except columns 8 and 9 are bad...
A_bad1 = A; A_bad1(9,8:9) = [9 7]
alfa = Sudoku(A_bad1);
fprintf('Sudoku(A_bad1) = %1d\n',alfa)
% This one is ok except rows 8 and 9 are bad...
A_bad2 = A; A_bad2(8:9,9) = [9 5]
alfa = Sudoku(A_bad2);
fprintf('Sudoku(A_bad2) = %1d\n',alfa)
% This one is ok except blocks (1,2),(1,3),(2,2),(2,3),(3,2), and (3,3)
% are bad...
A_bad3 = A; A_bad3(:,[6 7]) = A_bad3(:,[7 6])
alfa = Sudoku(A_bad1);
fprintf('Sudoku(A_bad3) = %1d\n',alfa)
% Does the method work on Rubik cubes?
Rubik = 1+floor(5*rand(3,3,3))
alfa = Sudoku(Rubik);
fprintf('Sudoku(Rubik) = %1d\n',alfa)


function alfa = Sudoku(A)
% alfa is 1 if A is a 9x9 matrix with the property that every row, column,
% and 3x3 block is made up of distinct positive integers.Otherwise, 
% alfa is 0.
[n1,n2] = size(A);
alfa = (n1==9 && n2==9);
if alfa
   % sort each column of A...
   C = sort(A);
   % sort each row of A...
   R = sort(A');
   % Proceed to make sure each column of C and R is (1:9)'...
   k=1;
   while alfa&&k<=9
      alfa = alfa && all(C(:,k)==(1:9)') && all(R(:,k)==(1:9)');
      k=k+1;
   end
   % Proceed to check the 3x3 blocks. 
   i=1;
   while alfa && i<=7
      j=1;
      while alfa && j<=7
         % A(i,j) is the upper left entry of the block.
         % Make a vector out of the entries of A(i:i+2,j:j+1)...
         v = [A(i:i+2,j) ; A(i:i+2,j+1) ; A(i:i+2,j+2)];
         alfa = alfa && all(sort(v)==(1:9)');
         j=j+3;
      end
      i=i+3;
   end
end