% Find all 3 by 3 magic squares. % Shows the use of a list of variables to keep track of whether % they have been assumed to have values or not yet. :-op(100, xfx, not_in). % a new infix operator. xfx defines associativity _ not_in []. D not_in [X | Rest]:- var(X),! , %added to reduce trail D not_in Rest. D not_in [X | Rest]:- nonvar(X), D\==X,!, %added to reduce trail D not_in Rest. % d(D) is for digit d(1). d(2). d(3). d(4). d(5). d(6). d(7). d(8). d(9). % nd(X, D) gets a new and different digit each time, But quickly. % D is a list of the variables representing digits in problem nd(Digit,DigitList):- nonvar(Digit),!. % cut added to reduce trail nd(Digit,DigitList):- var(Digit),!, d(X1), X1 not_in DigitList, Digit=X1. % a row has 3 different digits that add up to 15 row(X,Y,Z, DigitList):-nd(X,DigitList), nd(Y,DigitList), nd(Z,DigitList), X+Y+Z=:=15. col(X,Y,Z):- X+Y+Z=:=15. diag(X,Y,Z):- X+Y+Z=:=15. printrow(A,B,C):-write(A),write(B),write(C),nl. out(A,B,C,D,E,F,G,H,I):-nl, printrow(A,B,C), printrow(D,E,F), printrow(G,H,I). go:-go(More). go(More):-More=more, DigitList=[A,B,C,D,5,F,G,H,I], row(A,B,C,DigitList), row(D,5,F,DigitList), row(G,H,I,DigitList), col(A,D,G),col(B,E,H),col(C,F,I), diag(A,E,I), diag(G,E,C), out(A,B,C,D,E,F,G,H,I).