Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Notifications
Mark all as read
Code Reviews

Solving logical puzzle with negation and undefined aspects in Prolog

+7
−0

Assume this trivial logic puzzle which I have made up:

There are three boys, Fred, John and Max. No two of the boys have the same age. Max is older than John. Fred is not the oldest one. Question 1: Who is the oldest one? Question 2: What could be possible orderings by age?

Obviously, Max is the oldest one. And, from the given information the following two orderings are possible: Max,Fred,John and Max,John,Fred.

But, formulating this trivial logic puzzle in Prolog appeared to be surprisingly difficult (at least for me, as I am still learning Prolog). Particularly the statement "Fred is not the oldest one" caused me a lot of headache. While this restricts the solution space, it still leaves possibilities open with respect to whether Fred is older than John or not.

In the end, I came up with the following solution, which works with SWI Prolog if you issue the query ?- fromoldest(A,B,C).:

boys(Boys) :- Boys = [fred,john,max].

older(A,B,List) :-
    nth0(A_idx,List,A),
    nth0(B_idx,List,B),
    A_idx < B_idx.

fromoldest(A,B,C) :-
    boys(Boys),                 % there are three boys
    permutation(Boys,[A,B,C]),  % all of different age
    older(max,john,[A,B,C]),    % max is older than john
    dif(A,fred).                % fred is not the oldest

I would be glad to get feedback on this approach:

  • Is this idiomatic Prolog or what constructs should be preferred?
  • Are there more straightforward ways of solving this?
  • What about performance (like, use of permutation)?
Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

0 answers

Sign up to answer this question »

This community is part of the Codidact network. We have other communities too — take a look!

You can also join us in chat!

Want to advertise this community? Use our templates!

Like what we're doing? Support us! Donate