Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
48 views30 pages

Artificial Intelligence Lab: Laboratory Report

The laboratory report describes experiments conducted in the Artificial Intelligence Lab. It includes 3 units covering practical work related to: 1) Goal-based problems including implementing the Water Jug Problem and programming in Lisp. 2) Uninformed search algorithms including Depth First Search, Breadth First Search and Uniform Cost Search to find the path from ARAD to BUCHAREST on a map. 3) Informed search algorithms including using A* to solve the 8 puzzle problem. 4) Knowledge representations and logical reasoning including PROLOG programs for categorizing animals, solving linear equations, and defining family relationships.

Uploaded by

nikita
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views30 pages

Artificial Intelligence Lab: Laboratory Report

The laboratory report describes experiments conducted in the Artificial Intelligence Lab. It includes 3 units covering practical work related to: 1) Goal-based problems including implementing the Water Jug Problem and programming in Lisp. 2) Uninformed search algorithms including Depth First Search, Breadth First Search and Uniform Cost Search to find the path from ARAD to BUCHAREST on a map. 3) Informed search algorithms including using A* to solve the 8 puzzle problem. 4) Knowledge representations and logical reasoning including PROLOG programs for categorizing animals, solving linear equations, and defining family relationships.

Uploaded by

nikita
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Laboratory Report

 Artificial Intelligence Lab


MCL208

SCHOOL OF ENGINEERING AND TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Submitted By
Student Name Nikita Anand
System_Id 2020468119
Programme/Section MCA

Department Computer Science and Engineering


Semester 2nd Semester
Submitted To
Faculty Name Prof. Jasneet Kaur

PRACTICAL LIST
Unit Practical based on goal-based problems
1
a Lab Implementation of Water Jug Problem.
expt.1
b Lab Introduction to Lisp, and basic programming in Lisp like following:
expt.2
i. Write a LISP function to compute sum of squares.
ii. Write a LISP function to compute difference of squares. (if x > y
return x2 – y2, Otherwise y2 – x2).
iii. Write a Recursive LISP function which takes one argument as a
list and return last element of the list. (Do not use last predicate.)
iv. Write a Recursive LISP function which takes one argument as a
list and return list except last element of the list. (Do not use
butlast.)
v. Write a Recursive LISP function which takes one argument as a
list and return reverse of the list. (Do not use reverse predicate).
vi. Write a Recursive LISP function which takes two arguments first
an atom second a list returns a list after removing first occurrence
of that atom within the list.
vii. Write a Recursive LISP function which appends two lists together.
viii. Write a recursive LISP function which takes 2 lists as arguments
and returns a list containing alternate elements from each list.
c Lab Advance programming in Lisp like following: (Any 3)
expt.3
i. Write a function that compute the factorial of a number.(factorial
of 0 is 1, and factorial of n is n*(n-1)*...1.Factorial is defined only
for integers greater than or equal to 0.)
ii. Write a function that evaluate a fully parenthesized infix arithmetic
expression. For examples, (infix (1+ (2*3))) should return 7.
iii. Write a function that performs a depth first traversal of binary tree.
The function should return a list containing the tree nodes in the
order they were visited.
iv. Write a LISP program for water jug problem.
v. Write a LISP program that determines whether an integer is prime.
Unit Practical related to uninformed search algorithm.
2
a, b, Lab Refer following figure as map with distance details, Write a program in
expt.4 your preferred language to generate path from ARAD to BUCHREST,
analyze result obtained by
a) Depth First Search
b) Breadth First Search
c) Uniform Cost Search
c Lab i. Write a program in your preferred language to generate steps to solve Tower of
expt.5 Hanoi problem.
ii. Write a program in your preferred language to solve n-queens problem
Unit Practical related to informed search algorithm.
3
a,b,c Lab Write a program in your preferred language to solve the 8 puzzle Problem-
expt.6
using A* algorithm.
Unit Practical related to knowledge representations and logical reasoning (Any 2)
4
A Lab Write PROLOG program to Program to categorize animal characteristics.
expt.7
B Lab Write PROLOG program to solver for the linear equation A*X + B = 0.
expt.8 Let the predicate linear (A, B, X) return the root X of the equation.
c Lab Write a PROLOG program that answers questions about family members
expt.9 and relationships includes predicates and rules which define sister, brother,
father, mother, grandchild, grandfather and uncle. The program should be
able to answer queries such as the following:
father(x, Amit)
grandson(x, y)
uncle (sumit, puneet)
mother (anita, x)

1. Implementation of Water Jug Problem.


Program:
def pour(jug1, jug2):
max1, max2, fill = 5, 7, 4 #Change maximum capacity and final capacity
print("%d\t%d" % (jug1, jug2))
if jug2 is fill:
return
elif jug2 is max2:
pour(0, jug1)
elif jug1 != 0 and jug2 is 0:
pour(0, jug1)
elif jug1 is fill:
pour(jug1, 0)
elif jug1 < max1:
pour(max1, jug2)
elif jug1 < (max2-jug2):
pour(0, (jug1+jug2))
else:
pour(jug1-(max2-jug2), (max2-jug2)+jug2)

print("JUG1\tJUG2")
pour(0, 0)

OUTPUT

2. Introduction to Lisp, and basic programming in Lisp like following:


i. Write a LISP function to compute sum of squares.
Program:
(defun sumsqr(x y)
(write( + ( * x x )( * y y ))))
(sumsqr 2 3 )

OUTPUT

ii. Write a LISP function to compute difference of squares. (if x &gt; y return x 2 – y
2, Otherwise y 2 – x 2).
Program:
(defun diffsqr(x y)
(if ( > x y )
(write( - ( * x x ) ( * y y ) ))
(write( - ( * y y ) (* x x )))))
( diffsqr 2 3 )

OUTPUT

iii. Write a Recursive LISP function which takes one argument as a list and return
element of the list. (Do not use last predicate.)
Program:
(defun last_element(my_list)
(first(reverse my_list)))
(write (last_element '(p q r s)))

OUTPUT

iv. Write a Recursive LISP function which takes one argument as a list and return
list except last element of the list. (Do not use butlast.)
Program:
(defun exceptlast_element(my_list)
(reverse (cdr (reverse my_list))))
(write (exceptlast_element '(p q r s)))

OUTPUT

v. Write a Recursive LISP function which takes one argument as a list and return
reverse of the list. (Do not use reverse predicate).
Program:
(defun list-append (L1 L2)
(if (null L1) L2
(cons (first L1) (list-append (rest L1)
L2))))
(defun show-list-reverse (L)
(if (null L) nil
(list-append (show-list-reverse (rest L))
(list (first L)))))
(write (show-list-reverse '(1 2 3 4)))

OUTPUT

vi. Write a Recursive LISP function which takes two arguments first an atom second
a list returns a list after removing first occurrence of that atom within the list.
Program:
(defun remove(lst elt)
(cond((null lst)nil)
((equal(first lst)elt)(rest lst))
(elt(cons(first lst)
(remove(rest lst)elt)))))
(write(remove '(1 2 3 3 4 5)’3))

OUTPUT
vii. Write a Recursive LISP function which appends two lists together.
Program:
defun list-append (L1 L2)
(if (null L1) L2
(cons (first L1) (list-append (rest L1) L2))))
(write (list-append '(4 2) '(2 3 6)))

OUTPUT

viii. Write a recursive LISP function which takes 2 lists as arguments and returns a
list containing alternate elements from each list.
Program:
(defun alt( A B)
(cond ((and (endp A)(endp B))NIL)
((endp A) B)
((endp B) A)
(T (cons (car A) (alt B (cdr A))))))
(write(alt'(a b c d)'(1 2 3 4)))

OUTPUT

3. Advance programming in Lisp like following:


i. Write a function that compute the factorial of a number.(factorial of 0 is
1, and factorial of n is n*(n-1)*...1.Factorial is defined only for integers
greater than or equal to 0.)
Program:

(defun fact(n)
(if ( = n 1 )
1
(* n(fact(- n 1)))))
(write (fact 4))
OUTPUT

ii. Write a function that evaluate a fully parenthesized infix arithmetic


expression.
Program:

(write( + 6 5))

OUTPUT

iii. Write a LISP program that determines whether an integer is prime.


Program:
(defun forall(L P)
(if (null L)
T
(and (FUNCALL P (cAR L)) (forall (CDR L) P) )
)
)
(defun nums(start stop)

(setf L nil)

(loop ( when(> start stop) (return (reverse L)) )

(setf L (cons start L) )

(incf start)
)
)
(defun prime(N)

(forall (nums 2 (floor (sqrt N)) )

#'(lambda (d) (not (= (MOD N d) 0)))


)
)
(write(prime 2))
(write(prime 8))

OUTPUT

4. Refer following figure as map with distance details, Write a program in your
preferred language to generate path from ARAD to BUCHREST, analyze result
obtained by
Depth First Search
Program:
class node:
def __init__(self, name):
self.explored = 0
self.name = name
self.neighbours = {}

nodes = {}
start = 'Arad'
goal = 'Bucharest'
explored = []
frontier = []
path = []
f = open("F:\arad.txt", "r")
for line in f:
line = line.strip()
node1, node2, distance = line.split(",")
if node1 not in nodes:
nodes[node1] = node(node1)
if node2 not in nodes:
nodes[node2] = node(node2)
nodes[node1].neighbours[node2] = distance
nodes[node2].neighbours[node1] = distance

def initFrontier():
frontier.append(start)
nodes[start].parent = ''

def choosenode():
node = frontier.pop()
if testgoal(node):
print (goal)
pathcost = calpath(goal)
print ("path cost is {}".format(pathcost))
print ("path selected is {}".format(path))
exit()
return node

def calpath(cnode):
path.append(cnode)
if nodes[cnode].parent == '':
return 0
else:
cparent = nodes[cnode].parent
pathcost = calpath(cparent)+int(nodes[cnode].neighbours[cparent])
return pathcost

def testgoal(curnode):
if curnode == goal:
return True
return False

def graphsearch():
if not frontier:
print ("failure")
exit()
curnode = choosenode()
nodes[curnode].explored = 1
explored.append(curnode)
for neighbour in nodes[curnode].neighbours.keys():
if neighbour in frontier:
continue
if neighbour in explored:
continue
frontier.append(neighbour)
nodes[neighbour].parent = curnode
initFrontier()
while True:
graphsearch()
print (frontier)

OUTPUT

Breadth First Search 


Program:

dict_hn={'Arad':336,'Bucharest':0,'Craiova':160,'Drobeta':242,'Eforie':161,
'Fagaras':176,'Giurgiu':77,'Hirsova':151,'Iasi':226,'Lugoj':244,
'Mehadia':241,'Neamt':234,'Oradea':380,'Pitesti':100,'Rimnicu':193,
'Sibiu':253,'Timisoara':329,'Urziceni':80,'Vaslui':199,'Zerind':374}

dict_gn=dict(
Arad=dict(Zerind=75,Timisoara=118,Sibiu=140),
Bucharest=dict(Urziceni=85,Giurgiu=90,Pitesti=101,Fagaras=211),
Craiova=dict(Drobeta=120,Pitesti=138,Rimnicu=146),
Drobeta=dict(Mehadia=75,Craiova=120),
Eforie=dict(Hirsova=86),
Fagaras=dict(Sibiu=99,Bucharest=211),
Giurgiu=dict(Bucharest=90),
Hirsova=dict(Eforie=86,Urziceni=98),
Iasi=dict(Neamt=87,Vaslui=92),
Lugoj=dict(Mehadia=70,Timisoara=111),
Mehadia=dict(Lugoj=70,Drobeta=75),
Neamt=dict(Iasi=87),
Oradea=dict(Zerind=71,Sibiu=151),
Pitesti=dict(Rimnicu=97,Bucharest=101,Craiova=138),
Rimnicu=dict(Sibiu=80,Pitesti=97,Craiova=146),
Sibiu=dict(Rimnicu=80,Fagaras=99,Arad=140,Oradea=151),
Timisoara=dict(Lugoj=111,Arad=118),
Urziceni=dict(Bucharest=85,Hirsova=98,Vaslui=142),
Vaslui=dict(Iasi=92,Urziceni=142),
Zerind=dict(Oradea=71,Arad=75)
)
import queue as Q
#from RMP import dict_hn

start='Arad'
goal='Bucharest'
result=''

def BFS(city, cityq, visitedq):


global result
if city==start:
result=result+' '+city
for eachcity in dict_gn[city].keys():
if eachcity==goal:
result=result+' '+eachcity
return
if eachcity not in cityq.queue and eachcity not in visitedq.queue:
cityq.put(eachcity)
result=result+' '+eachcity
visitedq.put(city)
BFS(cityq.get(),cityq,visitedq)
def main():
cityq=Q.Queue()
visitedq=Q.Queue()
BFS(start, cityq, visitedq)
print("BFS Traversal from ",start," to ",goal," is: ")
print(result)

main()
OUTPUT

Uniform Cost Search

Program:

dict_hn={'Arad':336,'Bucharest':0,'Craiova':160,'Drobeta':242,'Eforie':161,
'Fagaras':176,'Giurgiu':77,'Hirsova':151,'Iasi':226,'Lugoj':244,
'Mehadia':241,'Neamt':234,'Oradea':380,'Pitesti':100,'Rimnicu':193,
'Sibiu':253,'Timisoara':329,'Urziceni':80,'Vaslui':199,'Zerind':374}

dict_gn=dict(
Arad=dict(Zerind=75,Timisoara=118,Sibiu=140),
Bucharest=dict(Urziceni=85,Giurgiu=90,Pitesti=101,Fagaras=211),
Craiova=dict(Drobeta=120,Pitesti=138,Rimnicu=146),
Drobeta=dict(Mehadia=75,Craiova=120),
Eforie=dict(Hirsova=86),
Fagaras=dict(Sibiu=99,Bucharest=211),
Giurgiu=dict(Bucharest=90),
Hirsova=dict(Eforie=86,Urziceni=98),
Iasi=dict(Neamt=87,Vaslui=92),
Lugoj=dict(Mehadia=70,Timisoara=111),
Mehadia=dict(Lugoj=70,Drobeta=75),
Neamt=dict(Iasi=87),
Oradea=dict(Zerind=71,Sibiu=151),
Pitesti=dict(Rimnicu=97,Bucharest=101,Craiova=138),
Rimnicu=dict(Sibiu=80,Pitesti=97,Craiova=146),
Sibiu=dict(Rimnicu=80,Fagaras=99,Arad=140,Oradea=151),
Timisoara=dict(Lugoj=111,Arad=118),
Urziceni=dict(Bucharest=85,Hirsova=98,Vaslui=142),
Vaslui=dict(Iasi=92,Urziceni=142),
Zerind=dict(Oradea=71,Arad=75)
)
import queue as Q

start='Arad'
goal='Bucharest'
result=''

def get_fn(citystr):
cities=citystr.split(',')
hn=gn=0
for ctr in range(0,len(cities)-1):
gn=gn+dict_gn[cities[ctr]][cities[ctr+1]]
hn=dict_hn[cities[len(cities)-1]]
return(hn+gn)

def printout(cityq):
for i in range(0,cityq.qsize()):
print(cityq.queue[i])

def expand(cityq):
global result
tot,citystr,thiscity=cityq.get()
nexttot=999
if not cityq.empty():
nexttot,nextcitystr,nextthiscity=cityq.queue[0]
if thiscity==goal and tot<nexttot:
result=citystr+'::'+str(tot)
return
print("Expanded city------------------------------",thiscity)
print("Second best f(n)------------------------------",nexttot)
tempq=Q.PriorityQueue()
for cty in dict_gn[thiscity]:
tempq.put((get_fn(citystr+','+cty),citystr+','+cty,cty))
for ctr in range(1,3):
ctrtot,ctrcitystr,ctrthiscity=tempq.get()
if ctrtot<nexttot:
cityq.put((ctrtot,ctrcitystr,ctrthiscity))
else:
cityq.put((ctrtot,citystr,thiscity))
break
printout(cityq)
expand(cityq)
def main():
cityq=Q.PriorityQueue()
thiscity=start
cityq.put((999,"NA","NA"))
cityq.put((get_fn(start),start,thiscity))
expand(cityq)
print(result)
main()

OUTPUT
5. i. Write a program in your preferred language to generate steps to solve Tower
of Hanoi problem.

Program:
def TowerOfHanoi(n , source, destination, auxiliary):
if n==1:
print("Move disk 1 from source",source,"to destination",destination)
return
TowerOfHanoi(n-1, source, auxiliary, destination)
print("Move disk",n,"from source",source,"to destination",destination)
TowerOfHanoi(n-1, auxiliary, destination, source)
n=4
TowerOfHanoi(n,'A','B','C')

OUTPUT

ii. Write a program in your preferred language to solve n-queens problem.

Program:

class QueenChessBoard:
def __init__(self, size):
self.size = size
self.columns = []
def get_size(self):
return self.size

def get_queens_count(self):
return len(self.columns)

def place_in_next_row(self, column):


self.columns.append(column)
def remove_in_current_row(self):
return self.columns.pop()

def is_this_column_safe_in_next_row(self, column):


row = len(self.columns)

for queen_column in self.columns:


if column == queen_column:
return False

for queen_row, queen_column in enumerate(self.columns):


if queen_column - queen_row == column - row:
return False
for queen_row, queen_column in enumerate(self.columns):
if ((self.size - queen_column) - queen_row
== (self.size - column) - row):
return False

return True

def display(self):
for row in range(self.size):
for column in range(self.size):
if column == self.columns[row]:
print('Q', end=' ')
else:
print('.', end=' ')
print()

def print_all_solutions_to_n_queen(size):
board = QueenChessBoard(size)
number_of_solutions = print_all_solutions_helper(board)
print('Number of solutions:', number_of_solutions)

def print_all_solutions_helper(board):
size = board.get_size()

if size == board.get_queens_count():
board.display()
print()
return 1

number_of_solutions = 0
for column in range(size):
if board.is_this_column_safe_in_next_row(column):
board.place_in_next_row(column)
number_of_solutions += print_all_solutions_helper(board)
board.remove_in_current_row()

return number_of_solutions
n = int(input('Enter n: '))
print_all_solutions_to_n_queen(n)

OUTPUT

6. Write a program in your preferred language to solve the 8 puzzle Problem-


using A* algorithm.
Program:

from copy import deepcopy


from colorama import Fore, Back, Style

DIRECTIONS = {"U": [-1, 0], "D": [1, 0], "L": [0, -1], "R": [0, 1]}
END = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]

# unicode
left_down_angle = '\u2514'
right_down_angle = '\u2518'
right_up_angle = '\u2510'
left_up_angle = '\u250C'

middle_junction = '\u253C'
top_junction = '\u252C'
bottom_junction = '\u2534'
right_junction = '\u2524'
left_junction = '\u251C'

bar = Style.BRIGHT + Fore.CYAN + '\u2502' + Fore.RESET + Style.RESET_ALL


dash = '\u2500'

first_line = Style.BRIGHT + Fore.CYAN + left_up_angle + dash + dash + dash +


top_junction + dash + dash + dash + top_junction + dash + dash + dash +
right_up_angle + Fore.RESET + Style.RESET_ALL
middle_line = Style.BRIGHT + Fore.CYAN + left_junction + dash + dash + dash +
middle_junction + dash + dash + dash + middle_junction + dash + dash + dash +
right_junction + Fore.RESET + Style.RESET_ALL
last_line = Style.BRIGHT + Fore.CYAN + left_down_angle + dash + dash + dash +
bottom_junction + dash + dash + dash + bottom_junction + dash + dash + dash +
right_down_angle + Fore.RESET + Style.RESET_ALL

def print_puzzle(array):
print(first_line)
for a in range(len(array)):
for i in array[a]:
if i == 0:
print(bar, Back.RED + ' ' + Back.RESET, end=' ')
else:
print(bar, i, end=' ')
print(bar)
if a == 2:
print(last_line)
else:
print(middle_line)
class Node:
def __init__(self, current_node, previous_node, g, h, dir):
self.current_node = current_node
self.previous_node = previous_node
self.g = g
self.h = h
self.dir = dir

def f(self):
return self.g + self.h

def get_pos(current_state, element):


for row in range(len(current_state)):
if element in current_state[row]:
return (row, current_state[row].index(element))

def euclidianCost(current_state):
cost = 0
for row in range(len(current_state)):
for col in range(len(current_state[0])):
pos = get_pos(END, current_state[row][col])
cost += abs(row - pos[0]) + abs(col - pos[1])
return cost

def getAdjNode(node):
listNode = []
emptyPos = get_pos(node.current_node, 0)

for dir in DIRECTIONS.keys():


newPos = (emptyPos[0] + DIRECTIONS[dir][0], emptyPos[1] +
DIRECTIONS[dir][1])
if 0 <= newPos[0] < len(node.current_node) and 0 <= newPos[1] <
len(node.current_node[0]):
newState = deepcopy(node.current_node)
newState[emptyPos[0]][emptyPos[1]] = node.current_node[newPos[0]]
[newPos[1]]
newState[newPos[0]][newPos[1]] = 0
# listNode += [Node(newState, node.current_node, node.g + 1,
euclidianCost(newState), dir)]
listNode.append(Node(newState, node.current_node, node.g + 1,
euclidianCost(newState), dir))

return listNode

def getBestNode(openSet):
firstIter = True

for node in openSet.values():


if firstIter or node.f() < bestF:
firstIter = False
bestNode = node
bestF = bestNode.f()
return bestNode

def buildPath(closedSet):
node = closedSet[str(END)]
branch = list()

while node.dir:
branch.append({
'dir': node.dir,
'node': node.current_node
})
node = closedSet[str(node.previous_node)]
branch.append({
'dir': '',
'node': node.current_node
})
branch.reverse()

return branch

def main(puzzle):
open_set = {str(puzzle): Node(puzzle, puzzle, 0, euclidianCost(puzzle), "")}
closed_set = {}

while True:
test_node = getBestNode(open_set)
closed_set[str(test_node.current_node)] = test_node

if test_node.current_node == END:
return buildPath(closed_set)

adj_node = getAdjNode(test_node)
for node in adj_node:
if str(node.current_node) in closed_set.keys() or str(node.current_node) in
open_set.keys() and open_set[
str(node.current_node)].f() < node.f():
continue
open_set[str(node.current_node)] = node

del open_set[str(test_node.current_node)]
if __name__ == '__main__':
br = main([[6, 2, 8],
[4, 7, 1],
[0, 3, 5]])

print('total steps : ', len(br) - 1)


print()
print(dash + dash + right_junction, "INPUT", left_junction + dash + dash)
for b in br:
if b['dir'] != '':
letter = ''
if b['dir'] == 'U':
letter = 'UP'
elif b['dir'] == 'R':
letter = "RIGHT"
elif b['dir'] == 'L':
letter = 'LEFT'
elif b['dir'] == 'D':
letter = 'DOWN'
print(dash + dash + right_junction, letter, left_junction + dash + dash)
print_puzzle(b['node'])
print()
print(dash + dash + right_junction, 'ABOVE IS THE OUTPUT', left_junction +
dash + dash)
OUTPUT
total steps: 24

──┤ INPUT ├──


┌───┬───┬───┐
│ 6 │ 2 │ 8 │
├───┼───┼───┤
│ 4 │ 7 │ 1 │
├───┼───┼───┤
│ │ 3 │ 5 │
└───┴───┴───┘

──┤ RIGHT ├──


┌───┬───┬───┐
│ 6 │ 2 │ 8 │
├───┼───┼───┤
│ 4 │ 7 │ 1 │
├───┼───┼───┤
│ 3 │ │ 5 │
└───┴───┴───┘

──┤ UP ├──
┌───┬───┬───┐
│ 6 │ 2 │ 8 │
├───┼───┼───┤
│ 4 │ │ 1 │
├───┼───┼───┤
│ 3 │ 7 │ 5 │
└───┴───┴───┘

──┤ RIGHT ├──


┌───┬───┬───┐
│ 6 │ 2 │ 8 │
├───┼───┼───┤
│ 4 │ 1 │ │
├───┼───┼───┤
│ 3 │ 7 │ 5 │
└───┴───┴───┘

──┤ UP ├──
┌───┬───┬───┐
│ 6 │ 2 │ │
├───┼───┼───┤
│ 4 │ 1 │ 8 │
├───┼───┼───┤
│ 3 │ 7 │ 5 │
└───┴───┴───┘

──┤ LEFT ├──


┌───┬───┬───┐
│ 6 │ │ 2 │
├───┼───┼───┤
│ 4 │ 1 │ 8 │
├───┼───┼───┤
│ 3 │ 7 │ 5 │
└───┴───┴───┘

──┤ LEFT ├──


┌───┬───┬───┐
│ │ 6 │ 2 │
├───┼───┼───┤
│ 4 │ 1 │ 8 │
├───┼───┼───┤
│ 3 │ 7 │ 5 │
└───┴───┴───┘

──┤ DOWN ├──


┌───┬───┬───┐
│ 4 │ 6 │ 2 │
├───┼───┼───┤
│ │ 1 │ 8 │
├───┼───┼───┤
│ 3 │ 7 │ 5 │
└───┴───┴───┘

──┤ DOWN ├──


┌───┬───┬───┐
│ 4 │ 6 │ 2 │
├───┼───┼───┤
│ 3 │ 1 │ 8 │
├───┼───┼───┤
│ │ 7 │ 5 │
└───┴───┴───┘

──┤ RIGHT ├──


┌───┬───┬───┐
│ 4 │ 6 │ 2 │
├───┼───┼───┤
│ 3 │ 1 │ 8 │
├───┼───┼───┤
│ 7 │ │ 5 │
└───┴───┴───┘

──┤ RIGHT ├──


┌───┬───┬───┐
│ 4 │ 6 │ 2 │
├───┼───┼───┤
│ 3 │ 1 │ 8 │
├───┼───┼───┤
│ 7 │ 5 │ │
└───┴───┴───┘

──┤ UP ├──
┌───┬───┬───┐
│ 4 │ 6 │ 2 │
├───┼───┼───┤
│ 3 │ 1 │ │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘

──┤ UP ├──
┌───┬───┬───┐
│ 4 │ 6 │ │
├───┼───┼───┤
│ 3 │ 1 │ 2 │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘

──┤ LEFT ├──


┌───┬───┬───┐
│ 4 │ │ 6 │
├───┼───┼───┤
│ 3 │ 1 │ 2 │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘

──┤ DOWN ├──


┌───┬───┬───┐
│ 4 │ 1 │ 6 │
├───┼───┼───┤
│ 3 │ │ 2 │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘

──┤ LEFT ├──


┌───┬───┬───┐
│ 4 │ 1 │ 6 │
├───┼───┼───┤
│ │ 3 │ 2 │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘

──┤ UP ├──
┌───┬───┬───┐
│ │ 1 │ 6 │
├───┼───┼───┤
│ 4 │ 3 │ 2 │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘

──┤ RIGHT ├──


┌───┬───┬───┐
│ 1 │ │ 6 │
├───┼───┼───┤
│ 4 │ 3 │ 2 │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘

──┤ DOWN ├──


┌───┬───┬───┐
│ 1 │ 3 │ 6 │
├───┼───┼───┤
│ 4 │ │ 2 │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘

──┤ RIGHT ├──


┌───┬───┬───┐
│ 1 │ 3 │ 6 │
├───┼───┼───┤
│ 4 │ 2 │ │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘

──┤ UP ├──
┌───┬───┬───┐
│ 1 │ 3 │ │
├───┼───┼───┤
│ 4 │ 2 │ 6 │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘

──┤ LEFT ├──


┌───┬───┬───┐
│ 1 │ │ 3 │
├───┼───┼───┤
│ 4 │ 2 │ 6 │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘

──┤ DOWN ├──


┌───┬───┬───┐
│ 1 │ 2 │ 3 │
├───┼───┼───┤
│ 4 │ │ 6 │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘

──┤ DOWN ├──


┌───┬───┬───┐
│ 1 │ 2 │ 3 │
├───┼───┼───┤
│ 4 │ 5 │ 6 │
├───┼───┼───┤
│ 7 │ │ 8 │
└───┴───┴───┘

──┤ RIGHT ├──


┌───┬───┬───┐
│ 1 │ 2 │ 3 │
├───┼───┼───┤
│ 4 │ 5 │ 6 │
├───┼───┼───┤
│ 7 │ 8 │ │
└───┴───┴───┘

──┤ ABOVE IS THE OUTPUT ├──

7. Write PROLOG program to Program to categorize animal characteristics.

Program:
animal(mammal,tiger,carnivore,stripes).
animal(mammal,hyena,carnivore,ugly).
animal(mammal,lion,carnivore,mane).
animal(mammal,zebra,herbivore,stripes).
animal(bird,eagle,carnivore,large).
animal(bird,sparrow,scavenger,small).
animal(reptile,snake,carnivore,long).
animal(reptile,lizard,scavenger,small).

OUTPUT

8. Write a PROLOG program that answers questions about family members


and relationships includes predicates and rules which define sister,
brother, father, mother, grandchild, grandfather and uncle. The program
should be able to answer queries such as the following: 
father(x, Amit) 
grandson(x, y) 
uncle (sumit, puneet) 
mother (anita, x)

Program:
female(pam).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
parent(pam,bob).
parent(tom,bob).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).
mother(X,Y):- parent(X,Y),female(X).
father(X,Y):- parent(X,Y),male(X).
sister(X,Y):-parent(Z,X),parent(Z,Y),female(X),X\==Y.
brother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\==Y.

OUTPUT

You might also like