Sunday, December 27, 2009

Logic Programming with Prolog (contd...)


Prolog code for Water-Jug Problem


Problem: You are given two jugs, a 4-gallon one and 3-gallon one. Neither has any measuring marks on it. There is a pump that can be used to fill the jugs with water. How can you get exactly 2 gallons of water into the 4-gallon jug?

Predicates
jug(integer,integer)
Clauses
jug(0,0):-write("\nFill 3g jug."),jug(0,3).
jug(0,3):-write("\nPour water from 3g jug to 4g jug."),jug(3,0).
jug(3,0):-write("\nFill 3g jug."),jug(3,3).
jug(3,3):-write("\nPour water from 3g jug to 4g jug until 4g jug is full."),jug(4,2).
jug(4,2):-write("\nEmpty 4g jug."),jug(0,2).
jug(0,2):-write("Pour water from 3g jug to 4g jug."),jug(2,0).
jug(2,0):-write("Goal state.").

jug(X,Y):-X>4,not(Y>3),write("\n4g jug overflowed."),not(jug(2,0)).
jug(X,Y):-not(X>4),Y>3,write("\n3g jug is overflowed."),not(jug(2,0)).
jug(X,Y):-X>4,Y>3,write("\nBoth jugs overflowed."),not(jug(2,0)).

jug(0,0):-write("\nFill 4g jug."),jug(4,0).
jug(4,0):-write("\nPour water from 4g to 3g jug."),jug(1,3).
jug(1,3):-write("\nEmpty 3g jug."),jug(1,0).
jug(1,0):-write("\nPour water from 4g to 3g jug."),jug(0,1).
jug(0,1):-write("\nFill 4g jug."),jug(4,1).
jug(4,1):-write("\nPour water from 4g jug to 3g jug until 3g jug is full."),jug(2,3).
jug(2,3):-write("\nEmpty 3g jug."),jug(2,0).
jug(2,0):-write("\nGoal State.").




Prolog code for Monkey-Banana Problem.


Problem: A hungry monkey finds himself in a room in which a bunch of bananas is hanging from the ceiling. The monkey, unfortunately cannot reach the bananas. However, in the room there are also a chair and a stick. The ceiling is just the right height so that a monkey standing on a chair could knock the bananas down with the stick. The monkey knows how to move around, carry other things around, reach for the bananas, and wave a stick in the air. What is the best sequence of actions for the monkey to take to acquire the lunch?

Domains
X,Y,Z = symbol
Predicates
in_room(symbol)
dexterous(symbol)
tall(symbol)
close(symbol,symbol)
under(symbol,symbol)
can_move(symbol,symbol,symbol)
get_on(symbol,symbol)
can_climb(symbol,symbol)
can_reach(symbol,symbol)
Clauses
in_room("monkey").
in_room("chair").
in_room("banana").
dexterous("monkey").
tall("chair").
can_move("monkey","chair","banana").
can_climb("monkey","chair").
can_reach(X,Y):-dexterous(X),close(X,Y).
close(X,"banana"):-get_on(X,Y),under(Y,"banana"),tall(Y).
close(Y,"floor"):-in_room(X),in_room(Y),in_room(Z),can_move(X,Y,Z).
close(_,_):-not(close("banana","floor")).
under("chair","banana").
under(Y,Z):-in_room(Y),in_room(Z),under(Y,Z).
get_on(X,Y):-can_climb(X,Y).