Search code examples
prologswi-prolog

How to find a list of people whose parents avarage age is the smallest


I already tried to do something myself and I think i'm pretty close to the solution but got stuck, any help would be appreciated.

Here is my data and code

parent_child(pam, bob).
parent_child(tom, bob).
parent_child(tom, liz).
parent_child(bob, ann).
parent_child(bob, pat).
parent_child(pat, jim).
parent_child(bob, peter).
parent_child(peter, jim).

female(pam).
female(liz).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
male(peter).

age(pam, 40). age(liz, 14). age(ann, 12). age(tom, 50). age(bob, 20). age(pat, 60). age(jim, 16).




Code

father(X, Y) :- parent_child(X, Y), male(X).
mother(X, Y) :- parent_child(X, Y), female(X).

two_parents(Y) :- father(_, Y), mother(_ ,Y).

min_average_age(Persons) :-
findall(Y-Avg,
        (   aggregate((sum(P), count),
                  (parent_child(Y,_), age(Y, P)),
                  (Sum, Count)
                  ),
            Avg is Sum / Count
        ),
        Pairs
),
aggregate_all(min(Avg), member(_-Avg, Pairs), Min),
findall(Y, member(Y-Min, Pairs), Persons).

I tried to use search for average age of parents but got only minimum age of parent_child(Parent,_), I also tried to check for a person to have 2 parents, and check those, but idk how to implement it


Solution

  • As hints:

    parent_child_age(P, C, Age) :-
        parent_child(P, C),
        age(P, Age).
    
    father_child_age(F, C, Age) :-
        male(F),
        parent_child_age(F, C, Age),
        age(F, Age).
    
    mother_child_age(M, C, Age) :-
        female(M),
        parent_child_age(M, C, Age),
        age(M, Age).
    
    child_avg_parents_age(C, Avg) :-
        father_child_age(_F, C, FAge),
        mother_child_age(_M, C, MAge),
        Avg is (FAge + MAge) / 2.
    

    Result:

    ?- child_avg_parents_age(C, A).
    C = bob,
    A = 45 ;
    false.