Ai lab 1 2 3 4 5
s(a,b).
s(a,c).
s(b,d).
s(b,e).
s(c,f).
s(c,g).
s(d,h).
s(e,i).
s(e,j).
s(f,k).
goal(f).
goal(j).
member(X,[X|_]).
member(X,[_|Tail]):-
member(X,Tail).
solve(Node,Solution):-
depthfirst([],Node,Solution).
depthfirst(Path, Node,[Node | Path]):-
goal(Node).
depthfirst(Path,Node,Sol):-
s(Node,Node1),
not(member(Node1,Path)),
depthfirst([Node | Path], Node1,Sol).
conc([X/L1],L2,[X|L3]):-
write('conc'),
write(X),
write(''),
write(L1),
write(' '),
write(L2),
conc(L1,L2,L3).
BFS
s(a,b).
s(a,c).
s(b,d).
s(b,e).
s(c,f).
s(c,g).
s(d,h).
s(e,i).
s(e,j).
s(f,k).
goal(f).
goal(j).
solve(Start,Solution):-
breadthfirst([[Start]],Solution).
breadthfirst([[Node | Path] ].[Node|Path]])
:-
goal(Node).
breadthfirst([Path | Paths] Solution):-
extend(Path,NewPaths),
write(NewPaths),
nl,
conc(Paths,NewPaths, Paths1),
breadthfirst(Paths1,Solution).
extend([NodePath],NewPaths):-
bagof([NewNode, Node | Path),(s(Node, NewNode),not(member(NewNode, [Node | Path]))),NewPaths),!.
extend([]).
conc([],L,L).
TOWER OF HANUAI
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).
WATERJUG
%Initial state: (0, 0) means both jugs are empty.
%Goal state: (2, _), where the first jug has exactly 2 liters of water.
%The capacity of the jugs
capacity(4, 3).
%Define possible actions: fill, empty, pour from one jug to another.
%Fill the 4-liter jug
action((X, Y), (4, Y)) :-
capacity(4, _),
X < 4.
%Fill the 3-liter jug
action((X, Y), (X, 3)) :-
capacity(_, 3),
Y < 3.
%Empty the 4-liter jug
action((X, Y), (0, Y)) :-
X > 0.
%Empty the 3-liter jug
action((X, Y), (X, 0)) :-
Y > 0.
%Pour water from the 4-liter jug into the 3-liter jug
action((X, Y), (NewX, NewY)) :-
capacity(_, MaxY),
X > 0,
Y < MaxY,
Transfer is min(X, MaxY - Y),
NewX is X - Transfer,
NewY is Y + Transfer.
%Pour water from the 3-liter jug into the 4-liter jug
action((X, Y), (NewX, NewY)) :-
capacity(MaxX, _),
Y > 0,
X < MaxX,
Transfer is min(Y, MaxX - X),
NewY is Y - Transfer,
NewX is X + Transfer.
%Define the search predicate to reach the goal state (2, _)
solve(Path) :-
search((0, 0), [(0, 0)], Path).
%Recursive search to find the solution path
search((2, _), Visited, Path) :-
reverse(Visited, Path).
search(State, Visited, Path) :-
action(State, NextState),
\+ member(NextState, Visited), % Avoid revisiting states
search(NextState, [NextState | Visited], Path).
MONKEY BANANA
move(state(middle,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,_,State2),
canget(State2).
Comments
Post a Comment