Tuesday, January 11, 2011

Prolog Examples II(AI,CS409)

Towers of Hanoi Problem

Fig. 2.3

you have N rings of increasing size and three pegs. Initially the three rings are
stacked in order of decreasing size on the first peg. You can move them between pegs but you must never stack a big ring onto a smaller one. What is the sequence of moves to move from all the rings from the first to the the third peg.

answers:

hanoi( N ):- 
      move( N, left, middle, right ).
move(1,X,Y,_) :-
      write('Move top disk from '),
      write(X),
      write(' to '),
      write(Y),
      nl.
move(N,X,Y,Z) :-
      N>1,
      M is N-1,
      move(M,X,Z,Y),
      move(1,X,Y,_),
      move(M,Z,Y,X).

Find Factoria (N!) of a number

factorial(0, 1).                                          % Factorial of 0 is 1.
factorial(N, FactN) :-
N > 0, % N is positive
Nminus1 is N - 1, % Calculate N minus 1
factorial(Nminus1, FactNminus1), % recursion
FactN is N * FactNminus1. % N! = N * (N - 1)!

Prolog Examples (AI,CS409)

monkeys banana problem

There is a monkey at the door into a room. In the middle of the room a banana is hanging from the ceiling. The monkey is hungry and wants to get the banana, but he cannot stretch high enough from the floor. At the window of the room there is a box the monkey may use.

The monkey can perform the following actions: 

Walk on the floor
Climb the box
Push the box around (if it is already at the box)
Grasp the banana if standing on the box directly under the banana. 

Answers code:

move(state(middel, onbox, middle, hasnot),
grasp,
state(middle, onbox, middle, has)).
move(state(P, onfloor, P, H),
climb,
state(P, onbox, P, H)).
move(state(P1, onfloor, P1, H),
push(P1, P2),
state(P2, onfloor, P2, H)).
move(state(P1, onfloor, B, H),
walk(P1, P2),
state(P2, onfloor, B, H)).
canget(state(_,_,_,has)).
canget(State1) :-
move(State1, Move, State2),
canget(State2).