Solve riddle in prolog - prolog

I want to solve this riddle in prolog:
The students Lily, Jack and Daisy go to the same university. All of them come from a different country and have different hobbies. They all go to a university in the USA, where one of them is living. Lily has better grades then the one who comes from Italy. Jack has better grades then the one who likes reading books. The best grades has the one who likes football. Jack comes from Germany and Daisy likes cooking.
Who is who (name, country, hobby, grades)?
The correct solution should be:
Lily, USA, Reading Books, Grade 2
Jack, Germany, Football, Grade 1
Daisy, Italy, Cooking, Grade 3
The Problem I have right now is that I don't know how I could solve this riddle. How should I define the facts and what's the best way to solve the riddle?

The trick to answer these puzzle questions in Prolog is to generate (retrieve) possible answers and then test them against the logical constraints. So, if Lily is person P1, then retrieve any person P2 and test if that person is from italy. And so forth with the other rules.
That means, in first instance, you need some clauses with possible countries, possible hobbies and possible grades. Not all possibilities are necessary, because some are already ruled out by the question.
The solution below, based on arbitrarily making Lily person 1, Jack person 2 and Daisy person 3.
Load in to Prolog and query who(P1,C1,H1,G1, P2,C2,H2,G2, P3,C3,H3,G3).
country(italy).
country(usa).
hobby(football).
hobby(reading).
grade(c:1).
grade(b:2).
grade(a:3).
who(lily,C1,H1,Grade1, jack,germany,H2,Grade2, daisy,C3,cooking,Grade3):-
country(C1), country(C3), C1 \= C3,
hobby(H1), hobby(H2), H1 \= H2,
grade(G1:Grade1), grade(G2:Grade2), grade(G3:Grade3),
G1 \= G2, G2 \= G3, G1 \= G3,
(C3=italy, G1#>G3),
(H1=reading, G2#>G1),
((H1=football, G1#>G2, G1#>G3); (H2=football, G2#>G1, G2#>G3)).

First, from filling in what we get from the first statement, we have the following.
(Lily, _, _, _)
(Jack,Germany, _, _)
(Daisy, _, Cooking, _)
Where the _ state we don't know something. I should also say that this isn't necessarily prolog, it's more common sense than anything.
We get the phrase "Lily has better grades then the one who comes from Italy", this means that Daisy is from Germany and Lily is from the USA- since Jack's from Germany.
(Lily, USA, _, Grade>Daisy)
(Jack,Germany, _, _)
(Daisy, Italy, Cooking, Grade<Lily)
Next, we have "Jack has better grades then the one who likes reading books", which gives us the fact that he would be the football player, and the next line tells us he has the best grade. We can then promptly fill up the remained and we get:
(Lily, USA, Reading, Grade2)
(Jack,Germany, Football, Grade1)
(Daisy, Italy, Cooking, Grade3)
There could be a program written in prolog that can solve this puzzle in a very roundabout way, but this puzzle is more specific than a general case.

Here is my take. It is essentially what #RdR has, just that I broke up the logic into more predicates, also to have a less overloaded who() main predicate.
name(lily). % (1)
name(jack).
name(daisy).
country(italy).
country(usa).
country(germany).
hobby(football).
hobby(cooking).
hobby(reading).
grade(1).
grade(2).
grade(3).
student(N,C,H,G):- % (2)
name(N), country(C), hobby(H), grade(G).
permute(P,X,Y,Z):- (4)
call(P,X), call(P,Y), call(P,Z) % (6)
, X\=Y, Y\=Z, X\=Z.
students(A,B,C):- (3)
permute(name,N1,N2,N3) % (5)
, permute(country,C1,C2,C3)
, permute(hobby,H1,H2,H3)
, permute(grade,G1,G2,G3)
, A = student(N1,C1,H1,G1) % (7)
, B = student(N2,C2,H2,G2)
, C = student(N3,C3,H3,G3)
.
who(A,B,C):- % (8)
students(A,B,C)
, A = student(lily,C1,H1,G1) % (9)
, B = student(jack,C2,H2,G2)
, C = student(daisy,C3,H3,G3)
, C2 = germany % (10)
, H3 = cooking
, (( C2=italy -> G1 < G2) % (11)
;( C3=italy -> G1 < G3))
, (( H1=reading -> G2 < G1)
;( H3=reading -> G2 < G3))
, (( H1=football -> G1 < G2, G1 < G3)
;( H2=football -> G2 < G1, G2 < G3)
;( H3=football -> G3 < G1, G3 < G2))
.
% Running it:
% ?- who(A,B,C).
% A = student(lily, usa, reading, 2),
% B = student(jack, germany, football, 1),
% C = student(daisy, italy, cooking, 3) ;
% false.
Discussion
So there is quite a bit going on here (which intrigued me), and several choices that could be made differently (hence it is probably a nice contrast to #RdR's solution).
As others pointed out one aspect is how to encode the information that is
given in the problem description. You can express it very concretely (solving
just this case), or be more general (to e.g. allow extending the problem to
more than 3 students).
What makes this problem different from similar others is that you have a mix
of constraints that affect either a singel student ("Jack comes from
Germany"), affect two students ("Lily's grades are better than the one from
Italy"), or involves all of them ("The one liking football has the best
grades").
Moreover, you have disjunction contraints ("They are all from different
contries, and have different hobbies"). Prolog is very good at going through
all the possible instances of a fact, but it is more complicated to have it
pick one instance and leave this one out for the next call of the predicate.
This forces you to find a way to get a set of values from a fact that are
pairwise distinct. (E.g. when Prolog settles for Lily's hobby being reading,
it mustn't also assign reading as Jack's hobby).
So after listing all known facts and their possible values (1) I first
defined a predicate student/4 (2) to simply state that a student has these
4 properties. This produces all possible combination of students and their
attributes, also allowing that they all have the same name, come from the
same country, asf.
It is a good example how to create a result set in Prolog that is way too
large, and then try to narrow it further down (like someone else wrote).
Further predicates could make use of this "generator" and filter more and more
solutions from its result set. This is also easier to test, on each stage you
can check if the intermediate output makes sense.
In a next predicate, students/3 (3), I try exactly what I mentioned
earlier, creating student instances that at least don't use the same
attribute twice (like two students having the same hobby). To achive this I
have to run through all my attribute facts (name/1, country/1, ...), get
three values for each, and make sure they are pairwise distinct.
To not having to explicitly do this for each of the attributes where the
implementation would be always the same except for the name of the
attribute, I constructed a helper predicate permute/4 (4) that I can pass
the attribute name and it will look up the attribute as a fact three times,
and makes sure the bound values are all not the same.
So when I call permute(name,N1,N2,N3) in students/3 (5) it will result in
the lookups call(P,X), call(P,Y), call(P,Z) (6) which results in the same as
invoking name(X), name(Y), name(Z). (As I'm collecting 3 different values
from always 3 facts of the same attribute this is effectively the same as doing the 3-permutations
of a 3-value set, hence the name of helper predicate.)
When I get to (7) I know I have distinct values for each student attribute,
and I just distribute them across three student instances. (This should
actually work the same without the student/4 predicate as you can always
make up structured terms like this on the fly in Prolog. Having the student
predicate offers the additional benefit of checking that no foolish students
can be constructed, like "student(lily, 23, asdf, -7.4)".)
So :- students(A,B,C). produces all possible combinations of 3 students and
their attributes, without using any of the involved attributes twice. Nice.
It also wraps the (more difficult) student() structures in handy
single-letter variables which makes the interface much cleaner.
But aside from those disjointness constraints we haven't implemented any of
the other constraint. These now follow in the (less elegant) who/3
predicate (8). It basically uses students/3 as a generator and tries to
filter out all unwanted solutions by adding more constraints (Hence it has
basically the same signature as students/3.)
Now another interesting part starts, as we have to be able not only to filter
individual student instances, but also to refer to them individually
("Daisy", "Jack", ...) and their respective attributes ("Daisy's hobby"
etc.). So while binding my result variable A, B and C, I pattern-match on
particular names. Hence the literal names lily, jack asf from (9). This
relieves me from considering cases where Lily might come in first, or as
second, or as third (as students/3 would generate such permutations). So
all 3-sets of students that don't come in that order are discarded.
I could just as well have done this later in an explicit constraint like N1 =
lily asf. I do so now enforcing the simple facts that Jack is from Germany
and Daisy likes cooking (10). When those fail Prolog backtracks to the
initial call to students/3, to get another set of students it can try.
Now follow the additional known facts about Lily's grades, Jack's grades, and
the grades of the football lover (11). This is particularly ugly code.
For one, it would be nice to have helper predicate that would be able return
the answer to the query "the student with attribute X". It would take the
current selection of students, A, B and C, an attribute name ('country') and a
value ('italy') and would return the appropriate student. So you could just
query for the student from Italy, rather than assuming it must be the second
OR the third student (as the problem description suggests that Lily herself
is not from Italy).
So this hypothetical helper predicate, let's call it student_from_attribute
would need another helper that finds a value in a student structure by name
and return the corresponding value. Easy in all languages that support some
kind of object/named tuple/record where you can access fields within it by
name. But vanilla Prolog does not. So there would be some lifting to be done,
something that I cannot pull off of the top of my head.
Also the who/3 predicate could take advantage of this other helper, as you
would need a different attribute from the student returned from
student_from_attribute, like 'grade', and compare that to Lily's grade.
That would make all those constraints much nicer, like
student_from_attribute([A,B,C], country, italy, S), attrib_by_name(S, grade,
G), G1 < G. This could be applied the same way to the reading and football
constraint. That would not be shorter, but cleaner and more general.
I'm not sure anybody would read all this :-). Anyway, these considerations made the puzzle interesting for me.

Related

Prolog: each player in a game plays a card. With partial knowledge of who played which cards, deduce who played the others

I'm trying to use Prolog to solve a simple game in which there are 3 players: Alice, Bob and Charlie. Each player secretly chooses a card to play, where cards can either be red or blue. The cards are then shuffled and turned over.
Assuming Alice's viewpoint, we know which card she played. Therefore if the revealed cards are blue, blue and red, and Alice played red, then she can deduce that both Bob and Charlie played blue. I'm struggling to define the appropriate causes for this. Here are my basic facts:
player(alice).
player(bob).
player(charlie).
color(blue).
color(red).
% The overturned cards -- all players can see these. Order is unimportant.
cards([blue, red, red]).
played(alice, blue).
From this, we should be able to deduce that Bob and Charlie each played red. I'm unsure how to tell Prolog that each of the three players played exactly one of the cards in the cards([blue, red, red]) fact. Or perhaps something along the lines of num_cards(blue, 1), num_cards(red, 2) would be better?
As a slightly more difficult example, it should be possible for the following facts to be used in deducing that Charlie played a red card (for example if Alice was able to peek at the card played by Bob):
player(alice).
player(bob).
player(charlie).
color(blue).
color(red).
% The overturned cards -- all players can see these. Order is unimportant.
cards([blue, red, red]).
played(alice, red).
played(bob, blue).
The most similar SO question I was able to find was this one, but I haven't been able to apply it to my problem. The CLPFD library definitely seems relevant.
Already for a really well-done background search: +1! The question you linked to and Boris's solution is indeed strongly related to this task.
First, I would like to point out that your task looks easy on the surface and is something that prima facie looks suitable for Prolog beginners to tackle. In my view, such tasks are not easy at all, and the difficulty quickly gets out of hand when additional knowledge (such as: who knows what, throughout different layers) must also be represented. I can well imagine that beginners who get such tasks as assignments will quickly walk away with the feeling "I could have easily solved this in Java, but it is impossible in Prolog". The fact that they could not have solved it in Java either usually does not bother them in the slightest.
In this concrete case, clpfd constraints are indeed a great fit. In fact, the global_cardinality/2 constraint which is for example available in SICStus Prolog solves both examples easily.
When using CLP(FD) constraints, the trick is to map your domain of interest to integers. In this case, I will (arbitrarily) use:
1 for blue
2 for red.
Also, I will simply use variables, one for each person, standing for the concrete "card" (i.e., integer) the person played. The idea is to specify what we know, and let the constraint solver figure out the rest.
So we have, in the first case:
?- global_cardinality([Alice,Bob,Charlie], [1-1,2-2]),
Alice = 1.
Alice = 1,
Bob = Charlie, Charlie = 2.
And in the second case:
?- global_cardinality([Alice,Bob,Charlie], [1-1,2-2]),
Alice = 2,
Bob = 1.
Alice = Charlie, Charlie = 2,
Bob = 1.
So in both cases, simply stating the given constraints suffices to deduce the single respective solution, just like you expected.
my hint needs a 'syntactical adaptation' to fit your question: from my viewpoint, it's essential to separate the facts expressing a particular query from entities identities: so, I propose a game/2 assessing the relation between a set of cards (those overturned, of course) and an association of player and played card, expressed as Player-Card:
player(alice).
player(bob).
player(charlie).
color(blue).
color(red).
game(Cs, [P-C|Ps]) :-
player(P), color(C),
select(C, Cs, Other),
game(Other, Ps),
\+ memberchk(P-_, Ps).
game([], []).
now, a lot of specific queries can be answered. For example
game([blue, red, red], [alice-blue,bob-B,charlie-C]).
B = C, C = red ;
B = C, C = red ;
false.
or
?- so:game([blue, red, red], [alice-blue,X,Y]).
X = bob-red,
Y = charlie-red ;
...
or
?- game([blue, red, red], [alice-red, bob-blue, Y]).
Y = charlie-red ;
...
To avoid duplicates solutions, setof/3 can be used.

Counting Prolog elements that meet a certain requirement

I am working through sample questions while studying using SWI-Prolog. This isn't a homework question, just exam revision using practice questions.
In this question I have a number of provided structures (dept) which includes a list within it, and I have to find the initial and surname of any head curator in a department that contains a total of 2 or more staff members with early history or modern history as their specialism.
The following Prolog database represents departments in a museum.
% A museum department is represented by the structure:
% dept(Area, Head_curator, Deputy_curator, Floor_staff).
%
% Floor_staff is a (possibly empty) list of staff structures and excludes
% the staff for Head_curator and Deputy_curator.
%
% Structures representing staff take the form:
% staff(Initial, Surname,
% cv(Specialism,Second_specialism,Years_employed)).
... Removed db entries that don't satisfy the question
dept(history,staff(d,steele,cv(early_history,modern_history,40)),
staff(d,owen,cv(modern_history,early_history,35)),
[staff(c,freud,cv(early_history,modern_history,30))]).
I am finding it very difficult to determine how to ensure that at least two of the Head OR the Deputy OR any member of the floor staff has a 1st or 2nd specialisation in early or modern history. I have created the following rules to extract this information:
head_curator(X) :- dept(_,X,_,_).
deputy_curator(X) :- dept(_,_,X,_).
floor_staff(X) :- dept(_,_,_,List), member(X,List).
exists(X) :-
head_curator(X);
deputy_curator(X);
floor_staff(X).
first_specialism((staff(_,_,cv(S,_,_,_)),S).
second_specialism((staff(_,_,cv(_,S,_,_)),S).
And I have written PROLOG below to extract the head curator's Initial and Surname - however, I am unsure of how to implement a 'count' to ensure any two people have the required specialism
q2(Initial,Surname) :-
dept(_,HeadCurator,_,List),
% forcing the same dept to be checked
HeadCurator = exists(staff(Initial,Surname,_)),
% check first and second specialisations
% somehow iterate through each person in this dept and
% stop once requirement reaches two people
%
% e.g. (first_specialisation(X) = modern_history;
% first_specialisation(X) = early_history;)
%
% (second_specialisation(X) = modern_history;
% second_specialisation(X) = early_history;)
I have attempted to flesh out the pseudocode outlining what I WOULD attempt as a solution to let you know that I have thought about it! I am just unsure of how to implement checking:
That numerous people have that 1st or 2nd specialisation
Returning true once two people are determined to have that specialisation

Solving Caliban problems with prolog

I'm working on solving a logic puzzle using prolog for school. Here's the clues:
Brown, Clark, Jones and Smith are 4 substantial citizens who serve their
community as achitect, banker, doctor and lawyer, though not necessarily
respectively.
Brown, who is more conservative than Jones but more liberal than Smith,
is a better golfer than the men who are younger than he is and has a
larger income than the men who are older than Clark.
The banker, who earns more than the architect, is neither the youngest
nor the oldest.
The doctor, who is a poorer golfer than the lawyer, is less conservative
than the architect.
As might be expected, the oldest man is the most conservative and has the
largest income, and the youngest man is the best golfer.
What is each man's profession?
hint: to rank people for weath, ability, relative age, etc
use the numbers 1,2,3,4 Be careful to state whether 1 represents,
e.g., youngest or oldest. Doing this makes comparisons easy to code.
To code (as follows) interprets all the relationships, given by the clues, as a list of lists, wherein each list defines the
%[profession,surname,politics,relative_age, relative_salary, golf_ability]:
profession(L) :- L = [[_,'Brown',_,_,_,_],[_,'Jones',_,_,_,_],[_,'Clark',_,_,_,_],
[_,'Smith',_,_,_,_]],
member([_,'Brown',P1,A6,M3,G3],L),
member([_,'Jones',P2,_,_,_],L),
member([_,'Clark',_,A3,_,_],L),
member([_,'Smith',P3,_,_,_],L),
moreconservative(P1,P2),
moreliberal(P1,P3),
bettergolfer(G3,younger(_,A6)),
richer(M3,older(_,A3)),
member(['banker',_,_,A1,M1,_],L),
member(['architect',_,P5,_,M2,_],L),
richer(M1,M2),
(A1 = 2;A1 = 3),
member(['doctor',_,P4,_,_,G1],L),
member(['lawyer',_,_,_,_,G2],L),
worsegolfer(G1,G2),
moreliberal(P4,P5),
member([_,_,4,4,4,_],L),
member([_,_,_,1,_,4],L).
I define the relative_politics,relative_salary,relative_age, and golf_ability relationships like so
EG:
richer(4,1).
moreconservative(4,1).
poorer(1,4).
poorer(1,3).
And it goes on for all relationships.
I think I have faithfully translated all of the clues to prolog but it just says fail when I query the database. EG:
?- profession(L).
fail.
I am using NU Prolog. I'm wondering if I made an error in my translation of the clues or I omitted a fact that is needed for the database to satisfy all the conditions of the list L.
bettergolfer(G3,younger(_,A6)) ... it doesn't work this way, in Prolog. Instead, have this
( member( X,L), age(X,AX), golf(X,GX),
( younger(AX,A6) -> better_golfer(G3,GX) ; true )),
.....
age( [_,_,_,A,_,_],A).
golf([_,_,_,_,_,G],G).
.....
this means, all the persons (including none) that are younger than Brown, must be poorer golfers than he is.
There is a catch here, too. Since we're told about the men younger than Brown, it means there must exist at least one such man (unlike in the mathematical definition of implication). We have to code this too. For example,
( member(X,L), age(X,AX), younger(AX,A6) -> true ),
.....
(using unique names for the new logvars of course). You'll have to make the same transformation for your richer(M3,older(_,A3)).
Great idea BTW, to have the comparison predicates defined in a generative fashion:
poorer(1,2).
poorer(1,3).
poorer(1,4).
poorer(2,3).
poorer(2,4).
poorer(3,4).
richer(A,B):- poorer(B,A)
If you were to define them as arithmetic comparisons, poorer(A,B):- A<B., you could potentially run into problems with uninstantiated variables (as recently discussed here).

English Sentence to Prolog clauses?

I am learning about Prolog recently and I came up with a question.
How do I say:
Any Employee drives, walks, rides or flies to work in Prolog clauses?
"Any" is where I am having problem with.
Here is my thought process.
Employee(tom). %tom is an employee (fact)
drives(X) :- Employee(X).
walks(X) :- Employee(X).
rides(X) :- Employee(X).
flies(X) :- Employee(X).
Is this a correct approach?
I think it's the other way around:
employee(X):- drives(X).
employee(X):- walks(X).
employee(X):- rides(X).
employee(X):- flies(X).
Plus facts for drives, walks, etc.
Whichever employee it is, one of these must hold. If it doesn't, then employee(X) fails.
This is, then, what it means under this Prolog database, that "any employee either flies, rides, etc.".
What you've written means, that given an X such that employee(X) holds, each of drives(X), walks(X), etc., will hold as well. I.e. "any employee walks, and drives, and rides, and flies" to work. (and of course, predicates must start with a lower case letter, always).

printing business cards - a kind of knapsack task

I am new to Prolog and I have some probably simple issue with a piece of code. This is a real world problem that arose last Friday and believe me this is not a CS Homework.
We want to print business cards and these can only be printed in blocks of 900 cards (100 sheets with 9 cards per sheet). The cards for anybody should not be distributed over several blocks. People ordered different amount of cards, E.G:
% "braucht" is german and means "needs"
braucht(anton,400).
braucht(berta,200).
braucht(claudia,400).
braucht(dorothee,100).
braucht(edgar,200).
braucht(frank,400).
braucht(georg,100).
I put together the following definition to find an appropriate block of 900 business cards:
block(0,[]).
block(N,[H|T]) :-
braucht(H,Nh),
% \+(member(H,T)),
D is N - Nh,
D >= 0,
block(D,T).
This produces a nice list of blocks of people whose cards fit together on a 900 cards block. But it stops working if I activate the commented line "\+member...." and just gives me a "false". But I need to assure that nobody is getting more than once on that block. What am I doing wrong here?
It seems that what you want to achieve is to set a constraint that H does not appear in the tail T of the list. However, T is still unbound when you call member/2, so that member(H, T) will succeed and hence \+ member(H,T) will fail.
If you don't want to use Constraint Programming, but use pure Prolog instead, you should use the check in the other direction and check whether H is already present in the list of people that has been aggregated up to that point. Something like:
block(0, List, List).
block(N, Rest, List) :-
braucht(H, Nh),
\+(memberchk(H, Rest)), % will fail when H is already in Rest
D is N-Nh,
D >= 0,
block(D, [H|Rest], List).
The predicate block/3 can be called from a predicate block/2:
block(N, List) :-
block(N, [], List).
If the second argument in your block predicate is the "output", then your problem is that T is a free variable, so member(_,T) will always succeed. For instance:
?- member(anton,T).
T = [anton|_]
T = [_,anton|_]
T = [_,_,anton|_]
and so on...

Resources