You are on page 1of 63
ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 ARTIFICIAL INTELLIGENCE LAB MAUAL B.TECH II YEAR —1 SEM (R20) (2022-2023) DEPARTMENT OF COMPUTATIONAL INTELLIGENCE (B.Tech-AIML) MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY (Autonomous Institution — UGC, Govt. of India) {Aliated to INTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC— ‘k’ Grad -ISO 9001.2015 Cercifiac) Maisarnmagudla, hutaplly (Post Via Hakimpst), Secunderabad ~ 500200, Telangana State, INDIA. Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 INDEX Intelligence Programs Using PROLOG Name of the Program Page No \Smdy of PROLOG Programming language and its Functions. Write simple facts for ihe statements using PROLOG. Vrite a program in PROLOG to implement simple arithmetic. ‘rite a program to implement Factorial, Fibonacci of a given number. Write predicates One converts centigrade temperatures to Fahrenheit, the ther checks if a temperature is below freezing, ite a program to Implement Depth First Search using PROLOG. Implementation of Breadth First Search for Tic-Tac-Toe problem. jrte a program to solve N-Queen problem rile a program to solve waler jug, problem using PROLOG /rite a program to solve the Monkey Banana problem. {Implementation of Traveling Salesman Problem, ‘Solve 8-puzzle problem using Best First Search. Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Artificial Intelligence Programs Using PROLOG Week-t Aim: Study of PROLOG Programming language and its Functions. Write simple facts for the statements using PROLOG. OBJECTIVE: Study of PROLOG. PROLOG-PROGRAMMING IN LOGIC PROLOG stands for Programming, In Logie — an idea that emerged in the early 1970’s to use logic as programming language. The early developers of this idea included Robert Kowaiski at Edinburgh (on the theoretical side), Marrten van Emden at Edinburgh (experimental demoustration) and Alian Colmerauer at Marseilles (iamplementation), David D.H. Warren's efficient implementation at Edinburgh in the id -1970°s greatly contributed to the popularity of PROLOG. PROLOG is a programming language centred around a small set of basic mechanisms, Including pattem matching, tree based data structuring and automatic backtracking, This Small set constitutes a surprisingly powerfil and flexible programming framework. PROLOG is especially well suited for problems that involve objects- in particular, structured objects- and relations between them, SYMBOLIC LANGUAG! PROLOG is a programming language for symbolic, non-numeric computation. It is especially ‘well suited for solving problems that involve objects and relations between objects. For example, it is an easy exercise in PROLOG to express spatial relationship between objects, such as the blue sphere is behind the green one. It is also easy to state a more general rule: if object X is closer to the observer than object Y. and object Y is closer than Z, then X must be closer than Z. PROLOG can reason about the spatial relationships and their consisteney with respect to the general rule, Features like this make PROLOG a powerful language for ArtIIcial LanguageA\,) and non- numerical programming. There are well-known examples of symbolic computation whose implementation in other standard languages took tens of pages of indigestible code, when the same algorithms were implemented in PROLOG, the result was a crystal-clear program easily fitting om one page Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 FACTS, RULES AND QUERIES Programing in PROIOG is accomplished by creatimg a database of facts and rules about objects, their properties, and their relationships to other objects. Queries then can be posed about the objects and valid conclusions will be determined and returned by the program Responses to user queries are determined through a form of inference control known as resohition. FOR EXAMPLE: a. Ram likes mango. b, Seema is a girl ©. Bill likes Cindy . Rose is red. e. John owns gold Program: Clauses likes(ram mango). gir(seema) red(rose), likes(bill cindy) owas(john gold) Output: queries ?-likes(ram, What) What= mango Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 likes(Who,cindy). Who= cindy ‘-red( What) ‘What= rose *-owns(Who, What) Who= john What= gold Viva Questions: 1- First create a source file for the genealogical logicbase application. Start by adding a few members of your family tree. It is important to be accurate, since we will be exploring family relationships. Your own knowledge of who your relatives are will verify the correctness of your Prolog programs. 2- Enter a two-argument predicate that records the parent-child relationship. One argument represents the parent, and the other the child. It doesn't matter in which order you enter the arguments, as long as you are consistent. Often Prolog programmers adopt the convention that parent(A,B) is interpreted "A is the parent of B”. 3- Create a source file for the customer order entry program. We will begin it with three record types (predicates), The first is customer/3 where the three arguments are arg) Customer name arg? City arg3 Credit rating (aaa, bbb, ete) 4- Next add clauses that define the items that are for sale. It should also have three arguments argl Item identification number Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 arg? Temname arg3 The reorder point for inventory (when at or below this level, reorder) 5- Next add an inventory record for each item. It has two arguments. arg Trem identification number (same as in the item record) arg? Amount in stock Assignment: Aim: Write facts for following: 1. Ram likes apple. Ram is taller then Mohan. 3. My name is Subodh. 4. Apple is fruit 5. Orange is fit 6. Ramis male AIM: Write simple queries for following facts Simple Queries Now that we have some facts in our Prolog program, we can consult the program in the listener and query, or call, the facts. This chapter, and the next, will assume the Prolog program contains only facts. Queries against programs with rules will be covered in a later chapter. Prolog queries work by pattern matching. The query pattern is called a goal. Ifthere is a fact that matches the goal, then the query succeeds and the listener responds with 'yes." If there is no matching faet, then the query fails and the listener responds with ‘no." Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Prolog's pattern matching is called unification. In the case where the logicbase contains only facts, tification sucezeds if the following three conditions hold, ‘The predicate named in the goal and logic base are the same. «© Both predicates have the same arity. © Allofthe arguments are the same, Before proceeding, review figure 3.1, which has a listing of the program so far. ‘The first query we will look at asks if the office is a room in the game. To pose this, we would enter that goal followed by a period at the listener prompt. 2 room(office) yes Prolog will respond with a ‘yes ifa match was found. If we wanted to know if the attie was a room, we would enter that goal. ? room(attic). No Solution:~ clauses Iikes(ram ,mango). gir(seema) red{rose). likes(bill cindy). owas(john ,gold) queries *-likes(ram, What) Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 What= mango elikes(Who,cindy). ‘Who= cindy red (What) What= rose -owns(Who, What), Who= john What= gold Viva Questions 1- Consider the following Prolog logic base easy(1). easy(2). easy(). gizmo(a,1) gizmo(b,3) gizmo(a,2) gizmo(d,5) gizmo(c,3). gizmo(a,3) gizmo(c,4). and predict the answers to the queries below, including all alternatives when the semicolon (;) is entered after an answer. 2 easy(2), 2 easy(X), Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 gizmo(a,X). 2. gizwmo(X,3). ‘2 gizmo(4,Y). > gizino(X\X) 2- Consider this logicbase, hharder(a, 1). harder(e,X). harder(b,4). harider(d.2. and predict the answers to these queries. 9 harder(a,X). 2 harder(e,X). hardex(X,1). harder(X,4). 3. Enter the listener and reproduce some of the example queries you have seen against locatiow/2. List or print location/2 for reference if you need it. Remember to respond with « semicolon (;) for multiple answers. Trace the query. 4- Pose queries against the genealogical logicbase that: © Confirm a parent relationship such as parent(dennis, diana) ‘¢ Find someone's parent such as parent(X, diana) ¢ Find someone's children such as pareat(dennis, X) ¢ List all parent-children such as parent(X,Y) 5- If parent/2 seems to be working, you can add additional family members to get a larger logicbase, Remember to include the corresponding male/1 or fenmle/1 predicate for each individual added. Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Week-2 ‘Aim: Write a program in PROLOG to implement simple arithmetic Prolog is not the programming language of choice for carrying out heavy-duty mathematics. It does, however, provide arithmetical capabilities. The pattem for evaluating arithmetic expressions is (where Expression is some arithmetical expression) X is Expression® ‘The variable X will be instantiated to the value of Expression. For example, 2Xis10+5. EX is10* 5S X=50 yes 2X is 10/5. X=2 Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 yes It is important to note that Expression is not evaluated by itself. You have to supply a variable (followed by the infix operator is2) to collect a result Other pre-defined Prolog arithmetic infix operators are greater than less than greater then or equal to less than or equal to Later in the course we will use op/3 to define operators of ow own, to make programs easier to read, Here we will return to the topic of defining recursive rules, with the addition of arithmetic ‘The built-in predicate display/1 can be used to reveal the ‘real’ constitution of expressions containing operators. For example, 9% display(X is 10+5 * 6/3) is_G292, +(10, (*(5, ©. 3))) shows that is/2 is the principal fumetor, then +, then / and so on, This is very handy if you are unsure about the effeets of your operator declarations. «© length’? tis often usefil to be able to calculate (or check) the length of a list. With arithmetic operators this is something that we can now do. The base is the empty list, which is obviously of length 0. This give us the Prolog clause: ength({ ], 0). The recursion simply requires that we add | for each item on the list? length HIT], N):- length(T, NI), NisNI +1 Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Week-3 Aim: Write a program to implement Factorial, Fibonacel of a given number. Program: fib(0.0). 1000.0), fibQ.1). ‘AHDEX, Ans) :- Xml is X-1 Xm? is X-2 ,fib(Xml Sub1), sib(Xm2,Sub2),Ans is ‘Sub1+Sub2, Output: fib(7.X), 3 White a Prolog program to calculate the factorial ofa given number. Progra fact(0.1). fac(N,F)-- ¢ % The below is for +ve factorial No> C NlisN-1 fact(NLF1), Fis NFL ) % The below is for -ve factorial No> ¢ Nlis N+, fact(NLF)), Fis N°FI ) ). Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 S cw pate iu Prolog 1-4.4, (64 bits) . By denier Biaz - * CSprrigst (2) 1999-2019 Daniel Dioz Eompiiiag Fi/nstarin! Vasht/Tth sex/Al/procticels/programs/1/fsct.pl for byte code Lelplate italia aon searetrpmstea i/o oe ne ea : Fi/satorielVeshu-Tth som/Al/precticale’progrens/Ifect.pl compiled, 25 lines read - 1047 bytes written, yes T= ace (5.8) yes T= act (0.8) Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Week-4 Write predicates One converts centigrade temperatures to Fahrenheit, the other checks if a temperature is below freezing. Program: © to {CF) -FisC *9/5 +32. % here freezing point is less than 32 Fahrenheit freezing(F) :-F —<32 ‘Output: ¢to_f(100,F) 12 © to_1(30,F) F=86 freezing(10). true fieezing(50). false Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Week-S ‘Waite a program (o Implement Depth First Search using PROLOG. Program: child(a,b). /*b is child ofa*/ child(a,c). eis child of a%/ child(a,d). /*d is child of a*/ child(b,e). /*e is child of b*/ child(b,). /*fis child of b*/ child(c,g). gis child ofc! childnode(a,G,{G}):- child(A,G). childnode(A,G,[X|L]):-child(A,X), childnode(X,G.L). path(A,G, [AlZ]):- childnode(A,G,Z). /* to find path between root to Leat*/ Output: 2 path(a,e.L), L=[a,be] Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Week-6 Implementation of Breadth First Search for Tic-Tac-Toe problem. ‘Theory/Description: The game Tie Tac Toe is also known as Noughts and Crosses or Xs and Os ,the player needs to take turns marking the spaces in a 3x3 grid with their own marks,if3 consecutive marks (Horizontal, Vertical, Diagonal) are formed then the player who owns these moves get won. Assume , Player 1 -X Player 2-0 Soa player who gets 3 consecutive marks first,they will win the game Let's have a discussion about how a board's data structure looks and how the Tie Tac Toe algorithin works Board's Data Structure: Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 ‘The cells could be represent as Center square, Corner, Edge as like below comer corner Number each square starts from 1 to 9 like following image Se 213/4]5/617/8]9 4-D Vector Consider a Board having nine elements vector. Each element will contain + 0 for blank © 1 indicating X player move © 2 indicating O player move Computer may play as X or © player. First player is always X. Move Table Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Itisa vector of 3°9 elements, each element of which is a nine element vector representing. ‘board position Total of 3°9(19683) elements in move table Move Table Index Current Board position New Board position o0000000 ‘000010000 000000001 020000001 000000002 000100002 00000010 002000010 Algorithm To make a move, do the following: View the vector (board) as a temary number and convert it to its corresponding decimal number. Use the computed number as an index into the move table and access the vector stored there. ‘The vector selected in step 2 represents the way the board will look after the move that shiould be made. So set board equal to that vector. Let's start with empty board Step 1:Now our board looks like 000 000 000 (tenary numiber) convert it into decimal no. The decimal no is 0 Step 2:Use the computed number ie 0 as an index info the move table and access the vector stored in New Board Position. ‘The new board position is 000 010 000 Step 3:The vector selected in step 2(000 010 000 ) represents the way the board will look after the move that should be made. So set board equal to that vector. After complete the 3rd step your board looks like\ Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 000 010 000 1900 000 000 {000 010 000 000 000 001 rT ‘With this game-board Weean move 222 222 202 Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 This process continues until the player get win or tie. Flowchart: Program: win(Board, Player) :- rowwin(Board, Player). win(Board, Player) :- colwin(Board, Player). win(Board, Player) -- diagzwin(Board, Player) rowwin(Board, Player) :- Board = [Player,Player,Player, .,,_,, ] rowwin(Board, Player) :- Board = [_,_,_.Player,Player,Player,_,_._] rowwin(Board, Player) :- Board = [_, Player Player, Player] Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 cohvin(Board, Player) :- Board = [Play colwvin(Board, Player) :- Board = [_Player, , Player, . Player, ] colwin{Board, Player) :- Board Player, , ,Player, , Player] in(Board, Player) :- Board = [Player,_, ,Player_,_. Player] diagwin(Board, Player) :- Board =[_, Player, ,Player,_,Player,_._] % Helping predicate for altemating play ina "self" game: other(3,0) other(o,x). game(Board, Player) :- win(Board, Player), !, write({player, Player, wins)) game(Board, Player) =~ other(Player, Otherplayer), move(Board Player, Newboard) ! display(Newboard), game(Newboard,Otherplayer). move((b,B,C,D,EF,G,H], Player, [Player,B,C.D.EF,G,H.I)). move((A,b,C,.D.E.F.G.HJ], Player, [A Player,C,D.E.F,G.HI). move((A.B.b,D-E.F.G.HJ], Player, [A.B Player,D.E.F,G.HI). move((A,B.C,b.E,F,G,HI], Player, [A.B,C-Player,E,F,G,HI)) move([A,B.C,.D,bF,G,HI], Player, [A,B.C.D Player,F,G.1D. Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 move([A,B.C,D,E,b.G.H], Player, [A,B,C,D,E Player, G.H.1). move([A,B,C,D,E,F,b,H,I], Player, [A,B,C,D,E,F Player,H,I)). move((A,B.C\D,E,F,Gb.I, Player, [A,B,C.D,EF,G,Player,t)) move((A,B.C\D,E,F,G,H.b], Player, [A.B,C\D.E,F,G\H Player) display(AB,C.D.E.F,G,HI)) :- write((A,B.C) lwrite((D,E,F))al, write((G.H.I]),nl.n1 selfgame :- game([b,b,b,b,b,b,b,b,b],x) % Predicates to support playing a game with the user: x can win in_one(Board) ;- move(Board, x, Newboard), win(Newboard, x). % The predicate orespond generates the computer's (playing o) reponse % from the current Board orespond(Board, Newboard) ‘- move(Board, 0, Newboard), win(Newboard, 0), ! orespond Board Newboard) - move(Board, 0, Newboard), not(x_can_win_in_one(Newboard)). orespond(Board.Newboard) ~ Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 ampve(Board, 0, Newboard) orespond(Board,Newboard) + not(member(b,Board)), wiite(Cats game!"), nl, ‘Newboard = Board. % The following translates fiom an integer description % of x's move to a board transformation, xmove([b,B,C,D,E,F,G.H,I], 1, [x,B,C,D,E.F,G.H.I)), xmove([A,b,C,D,E,P.G,H.I], 2, [A.C GH). xmove([A.B,b,DE,F.G.11], 3, [ABx,D.EF,G.HI)). xmove([A.B,C,b,E,F,G.HI], 4, [A,B,C .EF.GHI)), xmove([A,B,C,D.b,F,G,HI], 5, (A.B,C,D,x,F,G,H]I]), xmove([A,B,C,D,E,b,G,H,I], 6, [A,B,C,D,E.x,G,H,I)). xmove([A,B,C,D,E,F,b,H.I], 7, [A.B,C,D.EF.x,HI)). xmove([AB,C.DEFG,b]], 8, [AB,CDEFGxI)), xmove([A.B,C,D,E,F,G,H,b], 9, [A,B,C,D,E,F,G,H.x]). xmove(Board, _, Board) :- write(‘Ilegal move.), nl % The O-place predicate playo starts a game with the user. playo :- explain, playirom({b,b,b,b.,,b,b,b)). Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 explain := write(You play X by entering integer positions followed by a period.’), nl, display(.2.3.4,5,6,7,89)). playfrom(Board) -- win(Board, x), write‘You win'’) playfiom(Board) :- win(Board, 0), write(T win'. playfiom(Board) - read(N), xmove(Board, N, Newboard), display(Newboard), orespond(Newboard, Newnewboard), display(Newnewboard), playfiom(Newnewboard) ‘Output: Query: playo. ‘You play X by entering integer positions followed by a period. (1.2, 3] [4,5, 6] (7.8, 9] 1 [x,b, b] [b, b, b} [b,b, b] Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 x, 0, b] [b, b, b] {b, b, b] Lwin! true Another Output: fx, b, b] [b, b, b] Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 [b, b, b] [x, 0, b] [b,b,b] [b, bb] [x, 0, x] [b, b, b] [b, b, b] [x,0, x] {o,b, b] [b, bb] fx, 0, x] {o,x, b] [b, bb] [x, 0, x] {0,x, 0] [b,b, b] [x, 0, x] {o,x, o] fx, bb] Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 fx, 0, x] [o, x, 0] [x,0, b] {player, x, wins] Itme Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Week-7 ‘Write a program (o solve N-Queen problem Theory/Description: N-Queens Problem N - Queens problem is to place n - queens in such a manner on an n x n chessboard that no queens attack each other by being in the same row, columa or diagoual. It can be seen that forn =1, the problem as a trivial solution, and no solution exists form =2 and n~3, So first we will consider the 4 queens problem and then generate it to n - queens problem. Given a 4.x 4 chessboard and number the rows and column of the chessboard | through 4, 1 2 3 4 4x4 chessboard Since, we have to place 4 queens such as q: q2 q3 and qs on the chessboard, such that no two queens attack each otiser. In such a conditional each queen must he placed on a different row, ie., we put queen "i" on row Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Now, we place queen qr in the very first acceptable position (1, 1). Next, we put queen q; so that both these queens do not attack each other. We find that if we place q2 in column | and 2, then the dead end is encountered. Thus the first acceptable position for q: in column 3, ic. (2, 3) but then no position is left for placing queen 'qs' safely. So we backtrack one step and place the queen ‘go’ in (2. 4), the next best possible solution. Then we obtain the position for placing ‘qs which is (3, 2). But later this position also leads to a dead end, and no place is found where 'q.' can be placed safely. Then we have to backtrack till q:' and place it to (1, 2) and then all other queens are placed safely by moving qo to (2, 4), qs to (3, 1) and qs to (4, 3). That is, we get the solution (2, 4, 1, 3). This is one possible solution for the 4-queens problem. For another possible solution, the whole method is repeated for all partial solutions. The other solutions for 4 queens problems is (3, 1, 4,2) ie 1 23 4 o1 Q2 2 3 4 qa ‘The implicit tree for 4 - queen problem for a solution (2, 4, 1, 3) is as follows: Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Fig shows the complete state space for 4 - queens problem. But we can use backtracking method to generate the necessary node and stop if the next node violates the rule, ie., if two queens are attacking. 4 - Queens solution space with nodes numbered in DFS It can be seen that all the solutions to the 4 queens problem can be represented as 4 - tuples (1, x2, x3, x4) where xi represents the column on which queen "q\" is placed One possible solution for 8 queens problem is shown in fig: 1 2 3 4 5 6 7 8 a Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 ‘Thus, the solution for 8 -queen problem for (4, 6, 8, 2.7. 1. 3, 5). Iftwo queens are placed at position (i, j) and (k, 1). ‘Then they are on same diagonal only if (i- j)=k-lori+j=k+1 The first equation implies that j - 1=i-k. The second equation implies that j -1=k-i Therefore, two queens lie on the duplicate diagonal if and only if [j-l-ji- Place (k, i) returns a Boolean value that is true if the kth queen can be placed in column i. It tests both whether i is distinct from all previous costs x), X2,....Xx- 1 and whether there is no other queen on the same diagonal Using place, we give a precise solution to then n- queens problem. Program: % render solutions nicely ~ use_rendering(chess) 6% queens(+N, -Queens) is nondet @param ——_Queens is a list of column numbers for placing the queens. @author Richard A. O'Keefe (Lhe Cratt of Prolog) queens(N, Queens) Iength(Queens, N), board(Queens, Board, 0,.N,_, _), queens(Board, 0, Queens) board({], J], N,N, Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 board({_|Queens], [Col-VarsBoard], Col0, N, | [VR], VO) = Col is Col0+1, functor(Vars, £ N), constraints(N, Vars, VR, VC). board(Queens, Board, Col, N, VR, [ JVC). constraints(0, _,_,_)-! coustraints(N, Row, [RIRs}, [C|Cs}) = ang(N, Row, R-C), MisN-l, constraints(M, Row, Rs, C3) queens((], _, [D. queens([C{Cs}, Row0, {Col|Solution]) Row is Row0+1, select(Col-Vars, [C\Cs], Board), ang(Row, Vars, Row-Row), queens(Board, Row, Solution), = queens(8, Queens) */ Output: Query: queens(8, Queens) Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 ‘Queens = Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Week-8 ‘Write a program to solve water jug problem using PROLOG. Implementation of Depth First Search for Water Jug problem. ‘Theory/Deseription: In the water jug problem in Artificial Intelligence, we are provided with two jugs: one having the capacity to hold 3 gallons of water and the other has the capacity to hold 4 gallous of ‘water. There is no other measuring equipment available and the jugs also do not have any kind of marking on them. So, the ageat’s task here is to fill the 4-gallon jug with 2 gallons of water by using only these two jugs and no other material. Initially, both our jugs are empty So, to solve this problem, following set of niles were proposed: Production rules for solving the water jug problem Solttion: The state space for this problem can be described as the set of ordered pairs of integers (x,y) ‘Where. X represents the quantity of water in the 4-gallon jug X= 0,1,2,3,4 Y represents the quantity of water in 3-gallon jug Y=0,1,2,3 Start State: (0,0) Goal State: (2,0) Generate production rules for the water jug problem Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Production Rules: Rule Se z cay Xa) Process @w ‘Pur s-gatton ju = Cr GEYTESOy Cag), a tox, BS aartaEe CYT YSoy oD Gay Srass Yoo Eine aegallon ina? {Pour water from a-gallon jus into 4-eallon, antl g-gallon jug is full) CEYISVS=s aso) Yee) Ya) Pour water om 4-gallgn jus into g-xallon fag until a gallon jug ie fall) (Pour all water from g-gallon jug into 4 oY] R+¥<=3" tot {Pour all water from 4-gallon jug inte 3 gallon tue C0) jar 2 gallon water from 3 gallon jug into 4 Initialization: Start State: (0.0) Apply Rule 2: (KY]¥3) > 3) (Fill 3-gallon jug} Now the state is (X,3) Iteration 1 Cument State: (3) Apply Rule 7: (KY | XHY<4 “¥50) OY,0) {Pour all water fiom 3-gallon jug into 4-gallon jug} ‘Now the state is (3,0) Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Cument State : (3,0) Apply Rule 2: Q&Y|Y<3) > G3) {Fill 3-gallon jug} Now the state is (3.3) Iteration 3: ‘Current State:(3,3) Apply Rule 5 (WY XH¥o=4* ¥>0) GY-4-X) {Pour water fiom 3-gallon jug into 4-gallon jug until 4-gallon jug is full) Now the state is (4,2) Iteration 4: Current State : (4,2) Apply Rule 3: (XY X>0) ox) {Empty 4-gallon jug} Now state is (0,2) Iteration 5: Cument State : (0,2) Apply Rule 9: (0.2) (2.0) Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 {Pour 2 gallon water from 3 gallon jug into 4 gallon jug} Now the state is (2,0) Goal Achieved. Program: water_jug(X, Y) -X>4, Y<3, write(4L water jug overflowed’). water_jug(X,Y):-X<4, Y>3, write('3L water jug is overflowed.’),nl walter_jug(X, Y) :-X>4, Y>3, write(Both water jugs overflowed.’ al. water jug(X, Y) -(X==0, nl, write('4L:0 & 3L:3 (Action: Fill 3L jug.)), YY is 3, water_jug(X,YY)); ), nl, write(4L:4 & 3L:0 (Action: Fill 4L jug.)), XX is 4,water_jug(XX,¥)). =0, nl, write(‘4L:2 & 31:0 (Action: Goal state is reached...))); Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Oe: ni, write('4L:1 & 3L:3 (Action: Pour water from 4L jug to 31 jug.)), XX is X- 3, YY is 3, water_ng(XX, YY); (X==0, al, write(‘4L:3 & 3L:0 (Action: Pour water from 3L jug to 41. jug .)'), XX is 3, YY is 0, water_ng(XX,YY)); Oe: al, write(‘4L:1 & 3L:0 (Action: Empty 31 jug.)'), YY is 0, water_jug(X,YY)); =0, nl, write(’4L:3 & 3L:3 (Action: Fill 3L jug.)’), YY is 3, water_jugQYY)); nl, write(4L:4 & 31:2 (Action: Pour water fiom 31. jug to 4L jug until 4L jug is fi. )), XX is NHLYY is Y-1, water jue(XX,YY); ( =0, nl, write(‘4L:0 & 3L:1 (Action: Pour water from 4L jug to 3L jug.)’), XX is VY is X, water jugXX,YY)); (X==0, nl, write(‘4L:4 & 3L:1 (Action: Fill 4L jug.)), XX is 4, water_jug(XX,Y)); (& Y=", nl, write(4L:2 & 31:3 (Action: Pour water from 41 jug to 3L jug until 31 jug is full), XX is X-2, YY is Y+2, water_jug(XX,YY)); y="=3, nl, write(4L:2 & 3L:0 (Action: Empty 3L jug), YY is 0, water_jug(X,YY)): y="=2, nl, write(‘4L:0 & 3L:2 (Action: Empty 4L jug.)'), XX is 0, water_jug(XX,Y)); nl, write('4L:2 & 3:0 (Action: Pour water from 3L jug to 41. jug.)), XX is Y, YY is X, water jueQX,Y¥)), Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 4L:0 & 3L:3 (Action: Fill SL jug.) J4L:3 & SL:0 (Action: Pour water from SL jug to 4L jug .) 4L:3 & SL:3 (Action: Fill 3L jug.) J4L:4 & 31:2 (Action: Pour water from 3L jug to 41 jug until 4L jug Is full.) AL:0 & 3L:2 (Action: Empty 41 jug.) J4L:2 & 3L:0 (Action: Pour water from 3L jug to 4L jug.) |4L:2 & SL:0 (Action: Goal state is reached...) true Be water_jug(0.1). J4L.4 & 31.1 (Action: Fill 4t jug.) 4L:2 & SL:3 (Action: Pour water from 4L jug to 3L jug until 3L jug is full) AL:2 & 3L:0 (Action: Empty 31 jug.) |4L:2 & 3L-0 (Action: Goal state is reached...) Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Week-9 ‘Write a program to solve the Monkey Banana problem. In this prolog example, we will see one very interesting and fimnous problem, The Monkey and Banana Problem. Problem Statement Suppose the problem is as given below ~ A hungry monkey is in a room, and he is near the door The monkey is on the floor Bananas have been ining from the center of the ceiling of the room. ‘There is a block (or chair) present in the room near the window. ‘The monkey wants the banana, but cannot reach it. So how can the monkey get the bananas? Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 So if the monkey is clever enough, he can come to the block, drag the block to the center, climb on it, and get the banana. Below ate few observations in this case ~ Monkey can reach the block, if both of them are at the same level. From the above image, we can see that both the monkey and the block are on the floor Ifthe block position is not at the center, then monkey can drag it to the center If monkey and the block both are on the floor, and block is at the center, then the monkey can climb up on the block. So the vertical position of the monkey will be changed. When the monkey is on the block, and block is at the center, then the monkey can get the bananas. Now, let us see how we can solve this using Prolog. We will create some predicates as follows ‘We have some predicates that will move fiom one state to auother state, by performing action. When the block is at the middle, and monkey is on top of the block, and monkey does not have the banana (ie. has not state), then using the grasp action, it will change from has not state to have state From the floor, it can move to the top of the block (ie. on fop state), by performing the action climb. The push or drag operation moves the block from one place to another Monkey can move from one place to another using walk or move clauses. Another predicate will be canget(). Here we pass a state, so this will perform move predicate fiom one stateto another using different actions, then perform canget() on state 2. When we have reached to the state *has>’, this indicates ‘has banana’. We will stop the execution. Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Program: move(tate(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,oniloorP1,H), drag(P1.P2). state(P2,onfloor-P2,H)). move(state(P!oniloor.BH), walk(P1,2), state(P2,onfloor,B,H) canget(state(_,,_.has)). canget(Statel) = move(Statel, ,State2), canget(State2) Output: |% [monkey banana] compiling D:/TP Prolog/Sample_Codes/monkey_banana.pl for byte code. D//TP Prolog/Sample_Codes/monkey_banena.pl compiled, 17 lines read - 2167 bytes written, 19 ms (31 ms) yes | 2+ canget(state(atdoor, onfloor, atwindow, hasnot)), Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 yes | 2- trace The debugger will first creep -~ showing everything (trace) yes {uace} | 2- canget(state(atdoor, onfloor, atwindow, hasnot)). 11 Call: canget(state(atdoor onfloor,atwindow,hasnot)) ? 2.2 Call: move(state(atdoor,onfloor.atwindow,hasnot), 52, 92)? 22 Exit. move(state(atdoor onfloor,atwindow hasnt) walk(atdoor,_80),state(_80,onfloor,atwindo wahasnot)) ? 32 Call: canget(state(_80,onfloor,atwindow,hasnot)) ? 43 Call: move(state(_80,onfloor.atwindow,basnot),_110,_150) ? 43 Exit: move(state(atwindow.ontloor atwindow, hasnot) climb, state(atwindow,oubox,atwindow hasnot y? 53 Call: canget(state(atwindow,onbox,atwindow,hasnot)) ? 64 Call: move(state(atwindow,onbox,atwindow,hasnat), 165, 205) ? 64 Fail: move(state(atwindow,onbox,atwindowhasnot), 165, 193) ? 53 Fail: canget(state(atwindow,onbox,atwindow, basnot)) ? Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 43 Redo: move(state(atwindow, onfloor,atwindow, hasnot) climb,state(atwindow,onbox, atwindow,hasnot ye 43 Exit: move( tate(atwindow,on‘loor,atwindow.hasnot) drag(atwindow,_138),state(_138.onfloor,_138 shasnot)) ? $3 Call: canget(state(_138,onfloor,_138,hasnot)) ? 6 4 Call: move(state(_138,onfloor_138,hasnot),_168_208) ? 64 Exit: move(state(_138,onfloor,_138,hasnot),climb,state(_138,onbox,_138,hasuot)) ? 7 4 Call: canget(state(_138,onbox,_138,hasnot)) ? 85 Call: move(state(_138,onbox, 138,hasnot), 223, 263)? 85 Exit: move(state(middle,onbox, middle, hasnot) grasp, state( middle onbox,middle,has)) ? 9 5 Call: canget(state(middle,onbox,middle has) ? 9.5 Exit: canget(state{middle onbox,middle,has)) 9 74 Exit: cangel(state(middle,onbox,mniddle hasnot)) ? 53 Exit: canget(state(middle,onfloor,middle,hasnot)) ? 3.2 Exit: canget(state(atwindow,onfloor,atwindow,hasnot)) ? 11 Exit: canget(state(atdoor,onfloor,atwindow, hasnot)) ? (78 ms) yes Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Week-10 Implementation of Traveling Salesman Problem. Theory/Description: Ina state-space representation method, each state of the problem is represented by # node ofa graph or tree structure. In this case, the problem is translated as a search problem to determine the goal under specific operators and restrains. In this post, I will introduce Traveling Salesman Problem (TSP) as an example. Representation a problem with the state-space representation needs. (1). A set of states of the problem (2). A set of operators to operate between states of the problem (3). Initial state and final state(goal) ‘Traveling Salesman Problem (TSP) Consider the following situation. You are given a list of n cities with the distance between any two cities. Now, you have to start with your office and to visit all the cities only once each and retum fo your office. What is the shortest path can you take? This problem is called the Traveling Salesman Problem (TSP). Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Problem Formulation of TSP ‘To make the problem simple, we cousider 3-city-problem. Let's call the office (A Jand the 3 cities (B ) (C)(_D ) respectively. We initialize the problem state by {A} means the salesman departed from his office. As an operator, when he visited city-B, the problem state is updated to {A, B}, where the order of elements in { } is considered, When the salesman visited all the cities, (A, B, C, D} in this ease, the departed point A is automatically added to the state which means {A, B, C,D, A}. Therefore, the initial state of this TSP is {A} and the final state(goal) is {A, X1, X2, X3, A} where traveled distance is minimized. Taking each state as « node of a tree structure, we can represent this TSP as the following tree search problem {a} (>) f f \ ) \ J C) \ ) ( ) 7 VY YY \ yA {A,B,C,D} {A,B,C} {A,CB,D}—{A,C,D,B}_ {A,D,B,C}_—{A,D,C,B} Depth-first search ‘The depth-first search algorithm starts at the root node and explores as deep as possible along, each branch before taking backtracking. In our TSP, when a state node with all city labels is visited, its total distance is memorized. This information will later be used to define the shortest path. Let VISIT be a stack to save visited nodes, PATH be a set to save distances from the root node to the goal. ‘The depth-first algorithm can be written as Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Depth-first algorithm for TSP . Push root node to VISIT . If VISIT is empty, then go to 7. . Pop a node from VISIT, calls N. . If Nis the goal node, then append distance from root to N to PATH. . Push all child nodes of N to VISIT. |. Go to 2. . Get the minimum value from PATH, output the result. Done. Breadth-first search The depth-first search algorithm starts at the root node and explores all of the nodes at the present depth level before moving on to the nodes at the next depth level In our TSP, when a state node with all city labels is visited, its total distance is memorized. This information will later be nsed to define the shortest path Let VISIT be a queve to save visited nodes, PATH be a set to save distances from the root node to the goal. The breadth-first algorithm can be written as Breadth-first algorithm for TSP 1. Enqueue root node to VISIT 2. If VISIT is empty, then go to 7. 3. Dequeue a node from VISIT, calls N. 4, If Nis the goal node, then append distance from root to N to PATH. 5. Push all child nodes of N to VISIT. 6. Goto2. 7. Get the minimum value from PATH, output the result. Done. Heuristic Search In Brute-force search, all nodes are visited and the information from each node (distance fiom anode to anode) is not cousidered. This leads 1o a large amount of time and memory Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 consumption. To solve this problem, a heuristic search is a solution. The information of each state node is used to consider visiting a node or not. This information is represented by a heuristic function which commonly set up by user’s experiences. For example, we can define the hewistic fimetion by the distance from the root node to the present visit node, or the distance from the present visit node to the goal node. Rest-first search In the Best-first search, we use the information of distance from the root node to decide which, node to visit first. Let e(X) be the distance from the root node to node-X. Therefore, the distance from the root node to node-Y by visiting node-X is g(Y)=g(X)+d(X, Y), where d(x, Y) is the distance between X and Y. Let VISIT be a /ist to save visited nodes. The best-first algorithm can be written as Best-first algorithm for TSP . Append root node to VISIT . IF VISIT is empty, then search fails. Exit. . Get a node from the head of VISIT, calls N. . If Nis the goal node, then search succeeds, output the result. Exi . Push all child nodes of N to VISIT. Sort all elements X of VISIT in ascending order of g(X) 6. Goto2. A-algorithm (A*-algorithm) In the A algorithin search, we use the information of distance fiom the present visit node to the goal asa heuristic fiction, h(X). Let g(X) be the distence from the root node to node-X. In this case, we consider the priority of node visit order by f(X)=a(X)+-h(X). In real-world problems, itis impossible to obtain the exact value of h(X). In that case, an estimation value of h(X), h’(X), is used, However, setting h'(X) takes risks in falling into a local optimal answer. To prevent this problem, choosing h’(X) whieh h’(X)sh(X) for all X is recommended. In this case, it is known as A*-algorithm and it can be shown that the obtained answer is the global optimal answer In our experiment described in the following part, we are setting h’(X) as the sum of the minimum distance of all possible routes from each city which is not presented in the current Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 visit node label, and the present city. For example, if the present node is (A, D}, then city-B and C is not present in the label. Therefore, h’(D)-min(all possible route distance from, C)+min(all possible ronte distance fiom B)+min(all possible route distance fiom D). Let VISIT be a list to save visited nodes. The A-algorithm can be written as A-algorithm for TSP . Append root node to VISIT . IF VISIT is empty, then search fails. Exit. . Get a node from the head of VISIT, calls N. . IF N is the goal node, then search succeeds, output the result. Exit. . Push all child nodes of N to VISIT. Sort all elements X of VISIT in ascending order of f(X)=g(X)+h(X) |. Go to 2. Comparison between Search Algorithms We simulate the TSP with each introduced algorithm and focus on effectiveness as a search problem. Here, the effectiveness of a search problem is evaluated by the number of nodes visited to reach the answer and te effective branch number comparing to the tree's depth level. The effective branch number b* ofa problem where N nodes have been visited aud the answer is a d depth-level of the tree, is calculated by NHL = 1+ be § (4 1(b*)*F...1(b*)Ad. An algorithm with a smaller b* is a more effective algorithm. In this experiment, we use Newton's method to solve this equation to obiain the approximate value of b* Discussion on the number of visited nodes Number of cities |Depth-level |Breadth-first_|Depth-first A* Algorithm] 3 1 5. E} 16 16 65 65, Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 Discussion on the effective branch number Number of cities [Depth-level |Breadth-first|Depth-first_[Best-first__|A* Algorithm) 3 1. 3 3 15 15) 2.38] 2.38) 1.41 1.41) 2.55| 2.55 1.68 1.26) 2.84] 2.84) 2.05 1.34) 3.18| 3.18) 2.44 1.22' 2.28| 2.28) 2.83 1.46) Program: edge(a, b, 3). edge(a, ¢, 4). edge(a, d, 2). edge(a, e, 7). edae(b, ¢, 4). edge(b, 4, 6) edge(b, ¢, 3). edge(c, 4, 5). edge(e, ¢, 8). edge(4, e, 6) edge(b, a, 3). edge(e, a, 4) edge(d, a, 2). edge(e, a, 7). edge(e, b, 4) edge(d, b, 6) edge(e, b, 3). Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 edge(d,¢, 5). edge(e, c, 8). edeele, d, 6). edge(a, h, 2) edge(h, d, 1). (* Finds the length ofa list, while there is something in the list it increments N when there is nothing left it returns. * len({], 0). Jen({HIT], N):- len(T, X), N is X#1 Best path, is called by shortest path, It sends it the paths found in a path, distance format*/ best_path(Visited, Total):- path(a, a, Visited, Total, /*Path is expanded to take in distance so far and the nodes visited */ path(Start, Fin, Visited, Total) :- path(Start, Fin, [Start], Visited, 0, Total). /*This adds the stopping location to the visited list, adds the distance and then calls recursive tothe next stopping location along the path * Department of Computational Intelligence ARTIFICAL INTELLIGENCE LAB MANUAL 2022-2023 path(Start, Fin, CurreatLoe, Visited, Costn, Total) :~ edge(Start, StopLoe, Distance), NewCosin is Costn + Distance, \+ member(StopLoc, CurrentLoc), path(StopLoe, Fin, [StopLoc|CurrentLoc], Visited, NewCostn, Total). "When we find a path back to the starting point, make that the total distance and make sure the graph has touch every node*/ path(Start, Fin, CurreatLoe, Visited, Costu, Total) :~ edge(Start, Fin, Distance), reverse([Fin|CurrentLoc], Visited), len(Visited, Q), (Q=7 > Total is 100000; Total is Costn + Distance) /*This is called to find the shortest path, takes all the paths, collects them in holder ‘Then calls pick on that holder which picks the shortest path and retums it# shortest_path(Path):-setof{Cost-Path, best_path(Path,Cost), Holder),pick(Holder,Path) /* Js called, compares 2 distances, If cost is sanaller than beost, no need to go on. Cut it.*/ best(Cost-Holder,Beost-_,Cost-Holder):- Cost

You might also like