寻找表兄弟等的一般规则

时间:2015-05-28 05:12:31

标签: prolog

问题是写一个通用规则来找到任何级别的亲戚!

cousin(N,Child1,Child2).

如果Child1和Child2是Nth堂兄弟,那么这是真的。所以 cousin1(Child1,Child2)=堂兄(1,Child1,Child2)和 cousin2(Child1,Child2)=堂兄(2,Child1,Child2)等 为第三和第四甚至更高级别的堂兄弟。

到目前为止我所拥有的:

/* 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).

greatgrandparent(X, Z) :-
    parent(X, Y),
    parent(Y, P),
    parent(P, Z).

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

cousin2(Child1,Child2) :-
    greatgrandparent(Z, Child1),
    greatgrandparent(Z, Child2),
    \+sibling(Child1, Child2),
    \+cousin1(Child1, Child2),
    Child1 \= Child2.

无论输入什么值,都会返回false,所以显然我不知道我在做什么请帮助!

cousin(N,Child1,Child2) :-
    nth0(N, parent(Y1,Child1),Y1),
    nth0(N, parent(Y2,Child2),Y2),
    cousin1(Y1,Y2).

1 个答案:

答案 0 :(得分:1)

我试过了:

    % 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(Sib1,Sib2) :- parent(SomeParent,Sib1), 
             parent(SomeParent,Sib2), 
             \+ Sib1 = Sib2.

    % first person is ancestor of second person
    ancestor(Older,Younger,L) :-
             parent(Older,Younger),
             L is 1.
    ancestor(Older,Younger,Level) :- 
             parent(Older,Child),
             ancestor(Child,Younger,L),
             Level is L + 1. 


    %nth_cousin(Level,Cous1,Cous2) :- 
    %             ancestor(Sib1,Cous1,Level),
    %             ancestor(Sib2,Cous2,Level), 
    %             sibling(Sib1,Sib2).  

    nth_cousin(Level,Cous1,Cous2) :- 
             setof((Cous1,Cous2), Sib1^Sib2^(ancestor(Sib1,Cous1,Level), 
                                             ancestor(Sib2,Cous2,Level), 
                                             sibling(Sib1,Sib2)
                                            ), 
                   Cousins),
             member((Cous1,Cous2), Cousins),
             \+ (Cous2@<Cous1, member((Cous2,Cous1), Cousins)).  

实施例

    1 ?- nth_cousin(1,Cous1,Cous2).
    Cous1 = e,
    Cous2 = l ;
    Cous1 = e,
    Cous2 = m ;
    Cous1 = f,
    Cous2 = l ;
    Cous1 = f,
    Cous2 = m ;
    false.

    2 ?- nth_cousin(2,Cous1,Cous2).
    Cous1 = g,
    Cous2 = t ;
    Cous1 = h,
    Cous2 = t ;
    Cous1 = i,
    Cous2 = t ;
    false.
相关问题