Prolog
Aus ProgrammingWiki
Wiki-Quelltext dieser Seite.
<language>Prolog</language>
Welche Befehle dieser Interpreter versteht finden Sie hier: [[Prolog_Predicates|Prädikatliste]].
<code id="4d2b638530651">
mann(adam).
mann(tobias).
mann(frank).
frau(eva).
frau(daniela).
frau(ulrike).
vater(adam,tobias).
vater(tobias,frank).
vater(tobias,ulrike).
mutter(eva,tobias).
mutter(daniela,frank).
mutter(daniela,ulrike).
grossvater(X,Y) :-
vater(X,Z),
vater(Z,Y).
grossvater(X,Y) :-
vater(X,Z),
mutter(Z,Y).
</code>
<run id="4d2b6385308cd">
grossvater(X,frank).
</run>
<code id="4d2b6385306d9">
%queens(N,[N1,N2,...,NN]) is true if you can put a queen on an NxN
% in the ith rank of the nth file, s.t. no
% queen attacks any other queen.
queens(N,Qs) :-
range(1,N,Ns), queens(Ns,[],Qs).
queens(UnplacedQs, SafeQs, Qs) :-
selectq(Q, UnplacedQs, UnplacedQs1),
\+ attack(Q,SafeQs),
queens(UnplacedQs1,[Q|SafeQs],Qs).
queens([],Qs,Qs).
attack(X,Xs) :- attack(X, 1, Xs).
attack(X,N,[Y|_]) :- X is Y+N ; X is Y-N.
attack(X,N,[_|Ys]) :- N1 is N+1, attack(X,N1,Ys).
range(M,N,[M|Ns]) :- M < N, M1 is M+1, range(M1,N,Ns).
range(N,N,[N]).
selectq(X,[X|Xs],Xs).
selectq(X,[Y|Ys],[Y|Zs]) :- selectq(X,Ys,Zs).
%Try
%queens(4,P).
%
% The result P=[3,1,4,2] means the queens go like this:
% *****************
% 4 * * * Q * *
% *****************
% 3 * Q * * * *
% *****************
% 2 * * * * Q *
% *****************
% 1 * * Q * * *
% *****************
% 1 2 3 4
</code>
<run id="4d2b638530956">
queens(8,P).
</run>