MATLAB: Trying to make a sudoku puzzle generator

cleve's laboratoryfor loopor statementssudokuwhile loop

Before I start, I know that there are tons of Sudoku puzzle generators for MATLAB out there but none of them do what I would like. I am trying to create a Sudoku generator that will take a 9×9 array of zeros and replace the first row with a randomly generated array of the numbers 1-9. To do this, I am using the randperm function as follows:
numb=zeros(9,9);
numb(1,:)=randperm(9,9);
this part works fine. Where I am having issues is generating all following lines. As of right now, I am using a a different for loop for each row with nested for loops inside for each column. An example of the code I am using for the second row of the array is as follows:
for r=2;
for c=1;
numb(r,c)=randi(9);
for i=1:3;
while numb(r,c) == numb(r-1,i);
numb(r,c)=randi(9);
end
end
end
for c=2;
numb(r,c)=randi(9);
for i=1:3;
while numb(r,c) == numb(r-1,i) || numb(r,c) == numb(r,c-1);
numb(r,c)=randi(9);
end
end
end
for c=3;
numb(r,c)=randi(9);
for i=1:3;
while numb(r,c) == numb(r-1,i) || numb(r,c) == numb(r,c-1) || numb(r,c) == numb(r,c-2);
numb(r,c)=randi(9);
end
end
end
for c=4;
numb(r,c)=randi(9);
for i=4:6;
for j=1:(c-1);
while numb(r,c) == numb(r-1,i) || numb(r,c) == numb(r,c-j);
numb(r,c)=randi(9);
end
end
end
end
for c=5;
numb(r,c)=randi(9);
for i=4:6;
for j=1:(c-1);
while numb(r,c) == numb(r-1,i) || numb(r,c) == numb(r,c-j);
numb(r,c)=randi(9);
end
end
end
end
for c=6;
numb(r,c)=randi(9);
for i=4:6;
for j=1:(c-1);
while numb(r,c) == numb(r-1,i) || numb(r,c) == numb(r,c-j);
numb(r,c)=randi(9);
end
end
end
end
for c=7;
numb(r,c)=randi(9);
for i=4:6;
for j=1:(c-1);
while numb(r,c) == numb(r-1,i) || numb(r,c) == numb(r,c-j);
numb(r,c)=randi(9);
end
end
end
end
for c=8;
numb(r,c)=randi(9);
for i=4:6;
for j=1:(c-1);
while numb(r,c) == numb(r-1,i) || numb(r,c) == numb(r,c-j);
numb(r,c)=randi(9);
end
end
end
end
for c=9;
numb(r,c)=randi(9);
for i=4:6;
for j=1:(c-1);
while numb(r,c) == numb(r-1,i) || numb(r,c) == numb(r,c-j);
numb(r,c)=randi(9);
end
end
end
end
end
Can anyone tell me why the code as I have it written will work most of the time but not all the time to check and make sure there are no repeats in the second row, each column, and each 3×3 box? also, if anyone has any tips on how to extend this for loop or a better one to encorporate remaining rows, I'd love your input.

Best Answer

I like your randperm() idea. You can use it to do the scrambling without any for-loops at all.
You may safely transform a valid Suduko grid into another via:
  1. permuting the symbols '1'-'9'.
  2. permuting any three rows/columns within the same band (e.g. X([4 5 6],:) = X([6 5 4],:)
  3. permuting any three rows/columns of bands (e.g. X([1:3 4:6 7:9],:) = X([7:9 1:3 4:6],:)
  4. transposition (e.g. X = X')
Have fun!