简体   繁体   中英

The Grandma Birthday Puzzle in CLP(FD)

Can Prolog solve this puzzle with CLP(FD)? I see some problem
doing it with CLP(FD), since fractional cakes could be needed:

Edward is on his way to visit his Grandma, Who lives
at the end of the state. It's her birthday, and he want
to give her the cakes that he has made. Between his place
and her grandma house, he need to cross 7 toll bridges.
Before you can cross the toll bridge, you need to give them
half of the cakes you are carrying, but as they are kind trolls,
they each give you back a single cake. How many cakes does
Edward have to carry with him so he can reach his grandma
home with exactly 2 cakes?

A mathematician would possibly first derive and solve some closed
formula, or maybe see it in a blink. But lets do some Prolog. Since
I wasn't sure whether CLP(FD) works, I used CLP(Q).

The following code did the job:

:- use_module(library(clpq)).

grandmother(X,N,Y) :- N>1, !, M is N//2, 
      grandmother(X,M,H),
      K is N-M,
      grandmother(H,K,Y).
grandmother(X,1,Y) :- {Y = X/2+1}.

And the result was indeed integral, and as one can
verify all intermediate steps will be also integral:

?- grandmother(X,7,2).
X = 2.

But if the grandmother were in another land like:

grandmother(X,1,Y) :- {Y = X/3+5/4}.

Then the result wouldn't be integral:

?- grandmother(X,7,2).
X = 1101r4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM