“生成容易,怎么判断难度值.”先为我说这句话的冒失向楼主道歉。以下是我写的代码,能够按规则随机生成数独,但仅仅是能够而已。
program Project2;
{$APPTYPE CONSOLE}
type
TArr33 = array [0..2, 0..2] of Byte;
TArr99 = array [0..8, 0..8] of Byte;
var
Square: TArr99;
i: Integer;
Blank: Integer;
procedure Print(const A: TArr99);
var
i, j: Integer;
begin
for i:=0 to 8do
begin
for j:=0 to 8do
if A[i, j]>0 then
Write(A[i, j]: 2)
else
Write('_':2);
WriteLn
end
end;
procedure RandomFill(var A: TArr33);
var
t: array [0..8] of Integer;
Len: Integer;
i, j, k: Integer;
begin
for i:=0 to 8do
t:=i+1;
Len:=9;
for i:=0 to 2do
for j:=0 to 2do
begin
k:=Random(Len);
A[i, j]:=t[k];
t[k]:=t[Len-1];
Dec(Len)
end
end;
procedure Init(var A: TArr99);
var
Temp: TArr33;
i, j, k, l: Integer;
begin
for i:=0 to 2do
for j:=0 to 2do
begin
RandomFill(Temp);
for k:=0 to 2do
for l:=0 to 2do
A[i*3+k, j*3+l]:=Temp[k, l]
end
end;
function RegulateRow(var A: TArr99;
const Index: Integer): Integer;
var
i, j, k: Integer;
t: array [1..9] of array of Integer;
begin
Result:=0;
for i:=1 to 9do
SetLength(t, 0);
for i:=0 to 8do
if A[Index, i]<>0 then
begin
SetLength(t[A[Index, i]], Length(t[A[Index, i]])+1);
t[A[Index, i], Length(t[A[Index, i]])-1]:=i
end;
for i:=1 to 9do
if Length(t)>1 then
begin
k:=Random(Length(t));
for j:=0 to Length(t)-1do
if j<>k then
begin
A[Index, t[i, j]]:=0;
Inc(Result)
end
end
end;
function RegulateCol(var A: TArr99;
const Index: Integer): Integer;
var
i, j, k: Integer;
t: array [1..9] of array of Integer;
begin
Result:=0;
for i:=1 to 9do
SetLength(t, 0);
for i:=0 to 8do
if A[i, Index]<>0 then
begin
SetLength(t[A[i, Index]], Length(t[A[i, Index]])+1);
t[A[i, Index], Length(t[A[i, Index]])-1]:=i
end;
for i:=1 to 9do
if Length(t)>1 then
begin
k:=Random(Length(t));
for j:=0 to Length(t)-1do
if j<>k then
begin
A[t[i, j], Index]:=0;
Inc(Result)
end
end
end;
begin
Randomize;
Init(Square);
Blank:=0;
for i:=0 to 8do
begin
Blank:=Blank+RegulateRow(Square, i);
Blank:=Blank+RegulateCol(Square, i)
end;
Print(Square);
WriteLn('Blank=', Blank);
ReadLn
end.
但是,俺后来深入看了一下数独的一些网站,一个成功的数独题要满足以下几个条件:
1.有且仅有一组解
2.求解过程中每个数字都必须是通过逻辑推理填进去的,不能有任何猜测或代入的操作
3.日系数独题还强调点对称
这段代码没有一点能满足,因此设计“成功”的数独题是个小概率事件。