I am trying to write a matlab code to check a solved 9X9 sudoku problem. I can't seem to get it to work. Any ideas where I went wrong?

2 vues (au cours des 30 derniers jours)
function valid = sudoku (m)
valid = (size(m) == [9, 9]);
if (~valid)
fprintf('Sudoku: size must be 9x9\n');
return;
end;
valid = ((min(min(m)) >= 0) && (max(max(m)) <= 9));
if (~valid)
fprintf(['Sudoku: ', ...
'all entries must be integers between 0 and 9\n']);
return;
end;
% 1. check rows
for row = 1:9,
count = zeros(1, 9);
for col = 1:9,
data = m(row, col);
if (data > 0)
count(data) = count(data)+1;
end;
end;
valid = (max(count) <= 1);
if (~valid)
fprintf('Sudoku: row %i looks bad\n', row);
return;
end;
end;
% 2. check columns
for col = 1:9,
count = zeros(1, 9);
for row = 1:9,
data = m(row, col);
if (data > 0)
count(data) = count(data)+1;
end;
end;
valid = (max(count) <= 1);
if (~valid)
fprintf('Sudoku: col %i looks bad\n', col);
return;
end;
end;
% 3. check subsquares
for k = 0:8,
count = zeros(1, 9);
rowBase = 3*floor(k/3);
colBase = 3*mod(k,3);
for col = colBase+(1:3),
for row = rowBase+(1:3),
data = m(row, col);
if (data > 0)
count(data) = count(data)+1;
end;
end;
end;
valid = (max(count) <= 1);
if (~valid)
fprintf('Sudoku: subsquare %i looks bad\n', k+1);
return;
end;
end;
return;
  1 commentaire
dpb
dpb le 28 Avr 2016
The following jumped out at me altho it's a nit and probably the rarest of cases--
"fprintf(['Sudoku: ', ... 'all entries must be integers between 0 and 9\n']);"
...
'all entries must be integers between 1 and 9, inclusive\n']);

Connectez-vous pour commenter.

Réponses (1)

MHN
MHN le 28 Avr 2016
Modifié(e) : MHN le 28 Avr 2016
It works fine !
m = randi(9,9,9);
valid = (size(m) == [9, 9]);
if (~valid)
fprintf('Sudoku: size must be 9x9\n');
return;
end;
valid = ((min(min(m)) >= 1) && (max(max(m)) <= 9));
if (~valid)
fprintf(['Sudoku: ', ...
'all entries must be integers between 1 and 9\n']);
return;
end;
% 1. check rows
for row = 1:9,
count = zeros(1, 9);
for col = 1:9,
data = m(row, col);
if (data > 0)
count(data) = count(data)+1;
end;
end;
valid = (max(count) <= 1);
if (~valid)
fprintf('Sudoku: row %i looks bad\n', row);
return;
end;
end;
% 2. check columns
for col = 1:9,
count = zeros(1, 9);
for row = 1:9,
data = m(row, col);
if (data > 0)
count(data) = count(data)+1;
end;
end;
valid = (max(count) <= 1);
if (~valid)
fprintf('Sudoku: col %i looks bad\n', col);
return;
end;
end;
% 3. check subsquares
for k = 0:8,
count = zeros(1, 9);
rowBase = 3*floor(k/3);
colBase = 3*mod(k,3);
for col = colBase+(1:3),
for row = rowBase+(1:3),
data = m(row, col);
if (data > 0)
count(data) = count(data)+1;
end;
end;
end;
valid = (max(count) <= 1);
if (~valid)
fprintf('Sudoku: subsquare %i looks bad\n', k+1);
return;
end;
end;

Catégories

En savoir plus sur Sudoku dans Help Center et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by