要求创建对角线数独板 EN!
最编程
2024-06-01 18:44:57
...
:-use_module(library(clpfd)). % Constraint Programming Library
a(R):- % Main Predicate
l(9,R),m(l(9),R),append(R,V), % R is a list of 9 lists, each of length 9
V ins 1..9, % Values in R are between 1 and 9
transpose(R,C), % C is the transpose of R
d(0,R,D), % D is the diagonal of R
maplist(reverse,R,S),d(0,S,E), % E is the anti-diagonal of R
r(R), % All 3*3 blocks must contain numbers from 1 to 9
m(m(all_distinct),[R,C,[D,E]]), % Each row of R, each row of C, D and E must contain
% only distinct numbers
get_time(I),J is ceil(I), % Set J to a random number based on the current time
m(labeling([random_value(J)]),R). % Randomly find a solution for R
l(L,M):- % L is the length of M
length(M,L).
r([A,B,C|T]):- % For each group of 3 rows, the 3*3 blocks must
b(A,B,C),r(T);!. % contain distinct numbers
b([A,B,C|X],[D,E,F|Y],[G,H,I|Z]):- % Checks that the 3 3*3 blocks of 3 rows have
% distinct numbers inside them
all_distinct([A,B,C,D,E,F,G,H,I]),
b(X,Y,Z);!.
d(X,[H|R],[A|Z]):- % [A|Z] is the diagonal of [H|R]
nth0(X,H,A),
Y is X+1,
(R=[],Z=R;d(Y,R,Z)).
m(A,B):-
maplist(A,B).