image thumbnail
from Sudoku GUI by Johnny Brannbacka
Graphical user interface for creating and solving sudoku puzzles

[s,ss]=sudoku_construct(n)
function [s,ss]=sudoku_construct(n)

rand('state',round((now*1000-floor(now*1000))*1000));
e=1;
while e,
    s=zeros(9);
    s(1,:)=randperm(9);
    p1=find(~ismember(1:9,s(1,1:3)));
    p1=p1(randperm(length(p1)));
    s(2,1:3)=p1(1:3);
    s(3,1:3)=p1(4:6);
    [s,e]=sudokusolve(s);
end
ss=s;

ix=randperm(length(s(:)));

s(ix(1))=0;

i=1;
while length(find(s(:)==0))<n && i<length(ix),
    i=i+1;
    st=s;
    st(ix(i))=0;
    [st,ef]=sudokusolve(st,0);
    while i<length(ix) && ef~=0,
        i=i+1;
        st=s;
        st(ix(i))=0;
        [st,ef]=sudokusolve(st,0);
    end
    if ef==0,
        s(ix(i))=0;
    end
end

Contact us at files@mathworks.com