Search code examples
prolog

prolog finding first cousins in family


Trying to do a prolog question to find first cousins!

/* first person is parent of second person */
parent(a, b).
parent(b, f).
parent(a, d).
parent(f, g).
parent(a, k).
parent(f, h).
parent(k, l).
parent(f, i).
parent(k, m).
parent(l, t).
parent(b, e).

sibling(X,Y) :- parent(Z,X), parent(Z,Y), not(X=Y).

grandparent(X, Z) :-
    parent(X, Y),
    parent(Y, Z).

cousin1(Child1,Child2) :-
    grandparent(Y1,Child1),
    grandparent(Y2,Child2),
    not(sibling(Child1,Child2)),
    Y1=Y2 .

Seems to be working, but is there a way to stop it from returning true if the same child is input?

EDIT: final answer

cousin1(Child1,Child2) :-
    parent(Y1,Child1),
    parent(Y2,Child2),
    sibling(Y1,Y2).

Solution

  • Final answer!

     cousin1(Child1,Child2) :-
         parent(Y1,Child1),
         parent(Y2,Child2),
         sibling(Y1,Y2).