Sie sind auf Seite 1von 55

AI: Artificial Intelligence

(2180703)

2019-2020

LAB MANUAL
INDEX
Experiment No Title Page No Sign
1 Write a program to implement Tic-Tac-Toe game problem. 1
2 Write a program to implement BFS (for 8 puzzle problem or 7
Water Jug problem or any AI search problem)

3 Write a program to implement DFS (for 8 puzzle problem or 11


Water Jug problem or any AI search problem)

4 Write a program to implement Single Player Game (Using 17


Heuristic Function)

5 23
Write a program to Implement A* Algorithm

6 26
1)Write a program to solve N-Queens problem using Prolog
2) Write a program for the following task, Students who are
living in Rajkot, Students whose age is greater than 15 and
Students who has more than 60%.

1)Students who are living in Rajkot

2) Age Greater Than 15

3) Students who has more than 60%.

7 30
1)Write a program to solve 8 puzzle problem using Prolog.
2) Write a program to check wheter given value is character or
digit

3) Write a program to generate random number with respect to


entered digit.

4) Write a program to implement login system.

5) Write a program to implement login system recursively


35
1)Write a program to solve travelling salesman problem using
8 Prolog.
2) Write a program to display the element of give list.
3) Write a program for the family tree.

4) Write a program to check given element is in the list or not.

5) Write a program to find the largest number from the give


list.
9 45
1) Convert following Prolog predicates into Semantic Net
cat(tom).
cat(cat1).
mat(mat1).
sat_on(cat1,mat1).
bird(bird1).
caught(tom,bird1).
like(X,cream) :– cat(X).
mammal(X) :– cat(X).
has(X,fur) :– mammal(X).
animal(X) :– mammal(X).
animal(X) :– bird(X).
owns(john,tom).
is_coloured(tom,ginger).
2) Write a program to print the last element of the list.

3) Write a program to print the sum of the elements of the


given list

10 1) Write the Conceptual Dependency for following 49


statements.
(a) John gives Mary a book
(b) John gave Mary the book yesterday
2) Write a programme for File.

3) Monkey Banana problem.


MARWADI EDUCATION FOUNDATION’S GROUP OF INSTITUTIONS
FACULTY OF ENGINEERING, GAURIDAD CAMPUS.
DEPARTMENT OF COMPUTER ENGINEERING

Tutorial 1
Write a program to implement Tic-Tac-Toe game problem.
Answer:
 Program
#include <stdio.h>
#include <conio.h>

char square[10] = { 'o', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

int checkwin();
void board();

int main()
{
int player = 1, i, choice;

char mark;
do
{
board();
player = (player % 2) ? 1 : 2;

printf("Player %d, enter a number: ", player);


scanf("%d", &choice);

mark = (player == 1) ? 'X' : 'O';

if (choice == 1 && square[1] == '1')


square[1] = mark;

else if (choice == 2 && square[2] == '2')


square[2] = mark;

else if (choice == 3 && square[3] == '3')


square[3] = mark;

else if (choice == 4 && square[4] == '4')


square[4] = mark;

Heena Nakum (150570107063) P a g e 1 | 52


else if (choice == 5 && square[5] == '5')
square[5] = mark;

else if (choice == 6 && square[6] == '6')


square[6] = mark;

else if (choice == 7 && square[7] == '7')


square[7] = mark;

else if (choice == 8 && square[8] == '8')


square[8] = mark;

else if (choice == 9 && square[9] == '9')


square[9] = mark;

else
{
printf("Invalid move ");

player--;

}
i = checkwin();

player++;
}while (i == - 1);

board();

if (i == 1)
printf("==>\aPlayer %d win ", --player);
else
printf("==>\aGame draw");

return 0;
}

int checkwin()
{
if (square[1] == square[2] && square[2] == square[3])
return 1;

else if (square[4] == square[5] && square[5] == square[6])


return 1;
else if (square[7] == square[8] && square[8] == square[9])
return 1;

else if (square[1] == square[4] && square[4] == square[7])


return 1;

else if (square[2] == square[5] && square[5] == square[8])


return 1;

else if (square[3] == square[6] && square[6] == square[9])


return 1;

else if (square[1] == square[5] && square[5] == square[9])


return 1;

else if (square[3] == square[5] && square[5] == square[7])


return 1;

else if (square[1] != '1' && square[2] != '2' && square[3] != '3' &&
square[4] != '4' && square[5] != '5' && square[6] != '6' && square[7]
!= '7' && square[8] != '8' && square[9] != '9')

return 0;
else
return - 1;
}

void board()
{
system("cls");
printf("\n\n\tTic Tac Toe\n\n");

printf("Player 1 (X) - Player 2 (O)\n\n\n");

printf(" | | \n");
printf(" %c | %c | %c \n", square[1], square[2], square[3]);

printf(" | |_ \n");
printf(" | | \n");

printf(" %c | %c | %c \n", square[4], square[5], square[6])


printf(" | | \n");
printf(" | | \n");

printf(" %c | %c | %c \n", square[7], square[8], square[9]);

printf(" | | \n\n");
}

Output:-

Figure 1.1 entering the number by both the player


Figure 1.2 program will replace the x and o to that number

Figure 1.3 program will replace the x and o to that number


Figure 1.4 player one has won
Tutorial 2
Write a program to implement BFS (for 8 puzzle problem or Water
Jug problem or any AI search problem) .
Answer:
 Program
from collections import deque

def matchgoal(step,x,y,z):
#print("inside matchgoal",x,y,z)
s.append(x)
for word in step:
if word[4] == y:
#print(word)
#print(word[2],word[3],word[4])
#print('append called',s.append(word[2]))
matchgoal(step,word[2],word[3],word[4])

'''class Queue:
def init (self):
self.items = []

def isEmpty(self):
return self.items == []

def enqueue(self, item):


self.items.insert(0,item)

def dequeue(self):
return self.items.pop()

def size(self):
return len(self.items)
'''
x=0
y=0
n=0
start = [x,y]
goal = [2,n]
im = []
queue = deque()
queue8 = []
step = []
queue.append([0,0,0,0,0])
s=[]
#print(queue)
count=0

i=0
while queue:
#matchgoal(queue8)
count=count+1
if(count == 1200):
break
#print('inside queue8',queue8)
#print('inside',queue)
im = queue.popleft()
#print('this is im',im)
if im[0] == 2:
#print("Matched")
matchgoal(queue8,im[2],im[3],im[4])
for rule8 in reversed(s):
print('this is rule applied',rule8)
break
if im[0] < 4:
rule=1
x1=4
i=i+1
queue.append([4,im[1],rule,im[4],i])
queue8.append([4,im[1],rule,im[4],i])
# print('this is queue',queue)

if im[1] < 3 :
rule=2
y1=3
i=i+1
queue.append([im[0],3,rule,im[4],i])
queue8.append([im[0],3,rule,im[4],i])
# print('this is queue', queue)

if im[0] > 0:
rule=3
x2=0
i=i+1
queue.append([0,im[1],rule,im[4],i])
queue8.append([0,im[1],rule,im[4],i])

if im[1]>0:
rule=4
y2 =0
i=i+1
queue.append([im[0],0,rule,im[4],i])
queue8.append([im[0],0,rule,im[4],i])

if im[0]+im[1] >=4 and im[1]>0:


rule=5
x3=4
i=i+1
queue.append([x3,im[1]-(4-im[0]),rule,im[4],i])
queue8.append([x3,im[1]-(4-im[0]),rule,im[4],i])

if im[0]+im[1]>=3 and im[0]>0:


rule=6
y3=3
i=i+1
queue.append([im[0]-(3-im[1]),y3,rule,im[4],i])
queue8.append([im[0]-(3-im[1]),y3,rule,im[4],i])

if im[0]+im[1]<=4 and im[1]>0:


rule=7
y4=0
i=i+1
queue.append([im[0]+im[1],y4,rule,im[4],i])
queue8.append([im[0]+im[1],y4,rule,im[4],i])

if im[0]+im[1] <=3 and im[0]>0:


rule=8
x4=0
i=i+1
queue.append([x4,im[0]+im[1],rule,im[4],i])
queue8.append([x4,im[0]+im[1],rule,im[4],i])
#print('final',queue)

'''queue.append(lista)
print(queue)
queue.append([1,0])
print(queue)
list = queue.popleft()

print(list)
#list = queue.popleft()
#print(list[1]) '''

Output:-
Tutorial 3
Write a program to implement DFS (for 8 puzzle problem or Water
Jug problem or any AI search problem)
Answer:
 Program
#include<stdio.h>
#include<conio.h>
struct node
{int x, y;
struct node *next;
}*root, *left, *right;
void DFS()
{struct node *temp;
temp = left;
printf(“DFS Result\nStart State :: (%d , %d)\n”, root->x, root->y);
printf(“Possible DFS Result 1\n”);
while(1)
{printf(“(%d , %d)\n”, temp->x, temp->y);
if(temp->next == NULL)
break;

temp = temp->next;
}temp = right;
printf(“Possible DFS Result 2\n”);
while(1)
{printf(“(%d , %d)\n”, temp->x, temp->y);
if(temp->next == NULL)
break;
temp = temp->next;
}}int isNodePresent(struct node *nextState, int maxJug1, int maxJug2, int reqJug1, int reqJug2)
{struct node *temp;
if((nextState->x == reqJug1) && (nextState->y == reqJug2))
return(0);
if((nextState->x == maxJug1) && (nextState->y == maxJug2))
return(1);
if((nextState->x == 0) && (nextState->y == 0))
return(1);
temp = left;
while(1)
{if((temp->x == nextState->x) && (temp->y == nextState->y))
return(1);
else if(temp->next == NULL)
break;
else
temp = temp->next;
}temp = right;
while(1)
{if((temp->x == nextState->x) && (temp->y == nextState->y))
return(1);
else if(temp->next == NULL)
break;
temp = temp->next;
}return(0);
}struct node* genNewState(struct node *crntState, int maxJug1, int maxJug2, int reqJug1, int
reqJug2)
{int d;
struct node *nextState;
nextState = (struct node*)malloc(sizeof(struct node));
nextState->x = maxJug1;
nextState->y = crntState->y;
if(isNodePresent(nextState, maxJug1, maxJug2, reqJug1, reqJug2) != 1)
return(nextState);
nextState->x = crntState->x;
nextState->y = maxJug2;
if(isNodePresent(nextState, maxJug1, maxJug2, reqJug1, reqJug2) != 1)
return(nextState);
nextState->x = 0;
nextState->y = crntState->y;
if(isNodePresent(nextState, maxJug1, maxJug2, reqJug1, reqJug2) != 1)
return(nextState);
nextState->y = 0;
nextState->x = crntState->x;
if(isNodePresent(nextState, maxJug1, maxJug2, reqJug1, reqJug2) != 1)
return(nextState);
if((crntState->y < maxJug2) && (crntState->x != 0))
{d = maxJug2 – crntState->y;
if(d >= crntState->x)
{nextState->x = 0;
nextState->y = crntState->y + crntState->x;
}else{
nextState->x = crntState->x – d;
nextState->y = crntState->y + d;
}if(isNodePresent(nextState, maxJug1, maxJug2, reqJug1, reqJug2) != 1)
return(nextState);
}if((crntState->x < maxJug1) && (crntState->y != 0))
{d = maxJug1 – crntState->x;
if(d >= crntState->y)
{nextState->y = 0;
nextState->x = crntState->x + crntState->y;
}else{
nextState->y = crntState->y – d;
nextState->x = crntState->x + d;
}if(isNodePresent(nextState, maxJug1, maxJug2, reqJug1, reqJug2) != 1)
return(nextState);

}return(NULL);
}void generateTree(int maxJug1, int maxJug2, int reqJug1, int reqJug2)
{int flag1, flag2;
struct node *tempLeft, *tempRight;
root = (struct node*)malloc(sizeof(struct node));
root->x = 0; root->y = 0; root->next = NULL;
left = (struct node*)malloc(sizeof(struct node));
left->x = 0; left->y = maxJug2; left->next = NULL;
right = (struct node*)malloc(sizeof(struct node));
right->x = maxJug1; right->y = 0; right->next = NULL;
tempLeft = left;
tempRight = right;
while(1)
{flag1 = 0; flag2 = 0;
if((tempLeft->x != reqJug1) || (tempLeft->y != reqJug2))
{tempLeft->next = genNewState(tempLeft, maxJug1, maxJug2, reqJug1, reqJug2);
tempLeft = tempLeft->next;
tempLeft->next = NULL;
flag1 = 1;}
if((tempRight->x != reqJug1) || (tempRight->y != reqJug2))
{tempRight->next = genNewState(tempRight, maxJug1, maxJug2, reqJug1, reqJug2);
tempRight = tempRight->next;
tempRight->next = NULL;

flag2 = 1;}
if((flag1 == 0) && (flag2 == 0))
break;}}
void main()
{int maxJug1, maxJug2, reqJug1, reqJug2;
clrscr();
printf(“Enter the maximum capacity of jug1 :: “);
scanf(“%d”, &maxJug1);
printf(“Enter the maximum capacity of jug2 :: “);
scanf(“%d”, &maxJug2);
printf(“Enter the required water in jug1 :: “);
scanf(“%d”, &reqJug1);
printf(“Enter the required water in jug2 :: “);
scanf(“%d”, &reqJug2);
generateTree(maxJug1, maxJug2, reqJug1, reqJug2);
DFS();
getch();}

OUTPUT
Tutorial 4
Write a program to implement Single Player Game (Using
Heuristic Function)
Answer:
 Program
from copy import deepcopy
from tkinter import Button, Tk
from tkinter.font import Font
class Board:
def init (self, other=None):
self.player = 'X'
self.opponent = 'O'
self.empty = '.'
self.size = 3
self.fields = {}
for y in range(self.size):
for x in range(self.size):
self.fields[x, y] = self.empty
# copy constructor
if other:
self. dict = deepcopy(other. dict )
def move(self, x, y):
board = Board(self)
board.fields[x, y] = board.player
(board.player, board.opponent) = (board.opponent, board.player)
return board
def minimax(self, player):

if self.won():
if player:
return (-1, None)
else:
return (+1, None)
elif self.tied():
return (0, None)
elif player:
best = (-2, None)
for x, y in self.fields:
if self.fields[x, y] == self.empty:
value = self.move(x, y).__minimax(not player)[0]
if value > best[0]:
best = (value, (x, y))
return best
else:
best = (+2, None)
for x, y in self.fields:
if self.fields[x, y] == self.empty:
value = self.move(x, y).__minimax(not player)[0]
if value < best[0]:
best = (value, (x, y))
return best
def best(self):
return self. minimax(True)[1]
def tied(self):
for (x, y) in self.fields:
if self.fields[x, y] == self.empty:
return False
return True
def won(self):
# horizontal
for y in range(self.size):
winning = []
for x in range(self.size):
if self.fields[x, y] == self.opponent:
winning.append((x, y))
if len(winning) == self.size:
return winning
# vertical
for x in range(self.size):
winning = []
for y in range(self.size):
if self.fields[x, y] == self.opponent:
winning.append((x, y))
if len(winning) == self.size:
return winning
# diagonal
winning = []
for y in range(self.size):
x=y
if self.fields[x, y] == self.opponent:
winning.append((x, y))
if len(winning) == self.size:
return winning
# other diagonal
winning = []
for y in range(self.size):
x = self.size - 1 - y
if self.fields[x, y] == self.opponent:
winning.append((x, y))
if len(winning) == self.size:
return winning
# default
return None
def str (self):
string = ''
for y in range(self.size):
for x in range(self.size):
string += self.fields[x, y]
string += "\n"
return string
class GUI:
def init (self):
self.app = Tk()
self.app.title('TicTacToe')
self.app.resizable(width=False, height=False)
self.board = Board()
self.font = Font(family="Helvetica", size=32)
self.buttons = {}
for x, y in self.board.fields:
handler = lambda x=x, y=y: self.move(x, y)
button = Button(self.app, command=handler, font=self.font, width=2, height=1)
button.grid(row=y, column=x)
self.buttons[x, y] = button
handler = lambda: self.reset()
button = Button(self.app, text='reset', command=handler)
button.grid(row=self.board.size + 1, column=0, columnspan=self.board.size, sticky="WE")
self.update()
def reset(self):
self.board = Board()
self.update()
def move(self, x, y):
self.app.config(cursor="watch")
self.app.update()
self.board = self.board.move(x, y)
self.update()
move = self.board.best()
if move:
self.board = self.board.move(*move)
self.update()
self.app.config(cursor="")
def update(self):
for (x, y) in self.board.fields:
text = self.board.fields[x, y]
self.buttons[x, y]['text'] = text
self.buttons[x, y]['disabledforeground'] = 'black'
if text == self.board.empty:
self.buttons[x, y]['state'] = 'normal'
else:
self.buttons[x, y]['state'] = 'disabled'
winning = self.board.won()
if winning:
for x, y in winning:
self.buttons[x, y]['disabledforeground'] = 'red'
for x, y in self.buttons:
self.buttons[x, y]['state'] = 'disabled'
for (x, y) in self.board.fields:
self.buttons[x, y].update()
def mainloop(self):
self.app.mainloop()
if name == ' main ':
GUI().mainloop()

OUTPUT
Tutorial 5
Write a program to Implement A* Algorithm.
Answer:
 Program
import numpy

from heapq import *

def heuristic(a, b):

return (b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2

def astar(array, start, goal):

neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]

close_set = set()

came_from = {}

gscore = {start: 0}

fscore = {start: heuristic(start, goal)}

oheap = []

heappush(oheap, (fscore[start], start))

while oheap:

current = heappop(oheap)[1]

if current == goal:

data = []

while current in came_from:

data.append(current)

current = came_from[current]
return data

close_set.add(current)

for i, j in neighbors:

neighbor = current[0] + i, current[1] + j

tentative_g_score = gscore[current] + heuristic(current, neighbor)

if 0 <= neighbor[0] < array.shape[0]:

if 0 <= neighbor[1] < array.shape[1]:

if array[neighbor[0]][neighbor[1]] == 1:

continue

else:

# array bound y walls

continue

else:

# array bound x walls

Continue

if neighbor in close_set and tentative_g_score >= gscore.get(neighbor, 0):

continue

if tentative_g_score < gscore.get(neighbor, 0) or neighbor not in [i[1] for i in oheap]:

came_from[neighbor] = current

gscore[neighbor] = tentative_g_score

fscore[neighbor] = tentative_g_score + heuristic(neighbor, goal)

heappush(oheap, (fscore[neighbor], neighbor))

return False

nmap = numpy.array([
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1],

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],

[1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1],

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],

[1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1],

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
print(astar(nmap, (0, 0), (10, 13)))
OUTPUT
[(10, 13), (9, 12), (8, 11), (8, 10), (8, 9), (8, 8), (8, 7), (8, 6), (8, 5), (8, 4), (8, 3), (8, 2), (7, 1), (6, 2),
(6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (6, 9), (6, 10), (6, 11), (5, 12), (4, 11), (4, 10), (4, 9), (4, 8), (4,
7), (4, 6), (4, 5), (4, 4), (4, 3), (4, 2), (3, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (2,
10), (2, 11), (1, 12), (0, 11), (0, 10), (0, 9), (0, 8), (0, 7), (0, 6), (0, 5), (0, 4), (0, 3), (0, 2), (0, 1)]
Tutorial 6
Write a program to solve N-Queens problem using Prolog
Answer:
 Program
% render solutions nicely.

:- use_rendering(chess).

%% queens(+N, -Queens) is nondet.

% @param Queens is a list of column numbers for placing the queens.

% @author Richard A. O'Keefe (The Craft of Prolog)

queens(N, Queens) :-

length(Queens, N),

board(Queens, Board, 0, N, _, _),

queens(Board, 0, Queens).

board([], [], N, N, _, _).

board([_|Queens], [Col-Vars|Board], Col0, N, [_|VR], VC) :-

Col is Col0+1,

functor(Vars, f, N),

constraints(N, Vars, VR, VC),

board(Queens, Board, Col, N, VR, [_|VC]).

constraints(0, _, _, _) :- !.

constraints(N, Row, [R|Rs], [C|Cs]) :-

arg(N, Row, R-C),


M is N-1,

constraints(M, Row, Rs, Cs).

queens([], _, []).

queens([C|Cs], Row0, [Col|Solution]) :-

Row is Row0+1,

select(Col-Vars, [C|Cs], Board),

arg(Row, Vars, Row-Row),

queens(Board, Row, Solution).

Query

queens(8, Queens).

OUTPUT

2. Write a program for the following task, Students who are living in Rajkot, Students
whose age is greater than 15 and Students who has more than 60%. 1)Students who are
living in Rajkot2) Age Greater Than 15 3) Students who has more than 60%.

student("A","Rajkot",35,65).
student("B","Amreli",8,67).

student("C","Jamnagar",9,45).

student("D","Ahmedabad",45,35).

student("E","Rajkot",35,69).

1.Query

student(Name,City,Age,Spi),City="Rajkot".

Age = 35,
City = "Rajkot",
Name = "A",
Spi = 65

Age = 35,
City = "Rajkot",
Name = "E",
Spi = 69

2.Query

student(Name,City,Age,Spi),Age>15.

Age = 35,
City = "Rajkot",
Name = "A",
Spi = 65

Age = 45,
City = "Ahmedabad",
Name = "D",
Spi = 35

Age = 35,
City = "Rajkot",
Name = "E",
Spi = 69
3.Query

student(Name,City,Age,Spi),Spi>60.

Age = 35,
City = "Rajkot",
Name = "A",
Spi = 65

Age = 8,
City = "Amreli",
Name = "B",
Spi = 67

Age = 35,
City = "Rajkot",
Name = "E",
Spi = 69
Tutorial 7
1) Write a program to solve 8 puzzle problem using Prolog.
2) Write a program to check whether given value is character or digit
3) Write a program to generate random number with respect to
entered digit.
4) Write a program to implement login system.
5) Write a program to implement login system recursively
Answer:
 Program
solution([]).
solution([X/Y | Others]) :-
solution(Others),
member_queens(Y, [1, 2, 3, 4, 5, 6, 7, 8]),
noattack(X/Y, Others).
noattack(_, []).
noattack( X/Y,[X1/Y1 | Others]) :-
Y =\= Y1,
Y1 - Y =\= X1 - X,
Y1 - Y =\= X - X1,
noattack(X/Y, Others).
member_queens(Item, [Item | _]).
member_queens(Item, [_| Rest]) :-
member_queens(Item, Rest).
OUTPUT

2. Write a program to check whether given value is character or digit.


write("Enter value"),
read(X),
check(X,S),
write(S),nl.
check(X,S):-
X @>= 65,
X @=< 90, S="Uppercase".
check(X,S):-
X @>= 97,
X @=< 122, S="Lowercase".
check(X,S):-
X @>= 48,
X @=< 57, S="Digit".
goal
prog.
OUTPUT

3. Write a program to generate random number with respect to entered digit.


Domains
Clauses
main :-
write("Enter number"),read(S),X is random(S),write(X),nl.
Goal
main.
OUTPUT

4. Write a program to implement login system.


Domains
Clauses
getinput():-
write("Enter Username"),
read(Username),
write("Enter Password"),
read(Password),
check(Username,Password,X),
write(X),
nl.
check(avani,dalal,X) :-
X="Login Successfully !!".
goal
getinput.
OUTPUT

5. Write a program to implement login system recursively.


Domains
Clauses
getinput():-
write("Enter Username"),
read(Username),
write("Enter Password"),
read(Password),
check(Username,Password,X),
write(X),
nl.
check(avani,dalal,X) :-
X="Login Successful".
check(Username,Password,Y):-
Username \= avani,
Password \= dalal,
Y="Login Unsuccessful",
write(Y),
nl,getinput().
goal
getinput.
OUTPUT
Tutorial 8
Write a program to solve travelling salesman problem using Prolog.

Answer:
 Program
/* Nothing special with write_list.

If list is empty we do nothing,

and if something there we write head and call ourselves for tail. */

write_list([]).

write_list([H|T]):-

write(H),

write(" "),

write_list(T).

/* Is true if town X is in list of towns… */

townsmember(X,[X|_]).

townsmember(X,[_|L]):-

townsmember(X,L).

/* Is true if rib X is in list of ribs… */

ribsmember(r(X,Y,D),[r(X,Y,D)|_]).

ribsmember(X,[_|L]):-

ribsmember(X,L).

/* Is true if Route consists of all Towns presented in second argument */ alltown(_,

[]).

alltown(Route,[H|T]):-
townsmember(H,Route),

alltown(Route,T).

/* Is true if there is a way from Town1 to Town2, and also return distance between them */

way(Town1,Town2,Ways,OutWayDistance):-

ribsmember(r(Town1,Town2,D),Ways),

OutWayDistance = D.%/*

/* If next is uncommented then we are using non-oriented graph*/

way(Town1,Town2,Ways,OutWayDistance):-

ribsmember(r(Town2,Town1,D),Ways), /*switching direction here…*/

OutWayDistance = D.%*/

/* Is true if we could build route from Town1 to Town2 */

route(Town1,Town2,Ways,OutRoute,OutDistance):-

route1(Town1,[Town2],Ways,OutRoute,T1T2Distance),

%SWITCH HERE

way(Town2,Town1,Ways,LasDist), /* If you want find shortest way comment this line*/

OutDistance is T1T2Distance + LasDist. /* And make this: OutDistance = T1T2Distance.*/

route1(Town1,[Town1|Route1],_,[Town1|Route1],OutDistance):-

OutDistance = 0.

/* Does the actual finding of route. We take new TownX town and if it is not member of
PassedRoute,

we continue searching with including TownX in the list of passed towns.*/

route1(Town1,[Town2|PassedRoute],Ways,OutRoute,OutDistance):-

way(TownX,Town2,Ways,WayDistance),

not(townsmember(TownX,PassedRoute)), route1(Town1,[TownX,Town2|
PassedRoute],Ways,OutRoute,CompletingRoadDistance),
OutDistance = CompletingRoadDistance + WayDistance.

shorterRouteExists(Town1,Town2,Towns,Ways,Distance):-

ham(Town1,Town2,Towns,Ways,_,Other),

Other < Distance.

/* calling tsp(a,a,…. picks any one connected to a town and calls another tsp*/

tsp(Town1,Town1,Towns,Ways,BestRoute,MinDistance):-

way(OtherTown,Town1,Ways,_),

tsp(Town1,OtherTown,Towns,Ways,BestRoute,MinDistance).

/*Travelling Salesman Problem is Hammilton way which is the shortes of other ones.*/

tsp(Town1,Town2,Towns,Ways,BestRoute,MinDistance):-

ham( Town1,Town2,Towns,Ways,Route,Distance),

not(shorterRouteExists(Town1,Town2,Towns,Ways,Distance)),

BestRoute = Route,

MinDistance = Distance.

/*Hammilton route from Town1 to Town2 assuming that Town2->Town1 way exists.*/

ham(Town1,Town2,Towns,Ways,Route,Distance):-

route(Town1,Town2,Ways,Route,Distance),

%SWITCH HERE

alltown(Route,Towns), % if you want simple road without including all towns you could
uncomment this line

write_list(Route),

write("tD = ":Distance),nl.

% fail.

go:-
AllTowns = [a,b,c,d,e],

AllWays = [r(a,c,1), r(a,b,6), r(a,e,5), r(a,d,8), r(c,b,2), r(c,d,7), r(c,e,10), r(b,d,3), r(b,e,9),
r(d,e,4)],

tsp(a,a,AllTowns,AllWays,Route, Distance),

write("Finally"),nl,

write_list(Route),

write("tMin_D = ":Distance)

OUTPUT

2. Write a program to display the element of give list.

Domain

Clause

printlist([]).

printlist([X|Y]):-

write(X), nl,

write(Y).
goal

printlist([1,2,3,4]).

Screenshots: -

3. Write a program for the family tree.

domains

X,Y = String

Predicates:-

male("Rohan").

male("Sonu").

male("Monu").

male("Sam").

male("John").

male("Gautam").

male("Numa").

male("Rosh").

male("Posh").

female("Rina").

female("Nita").

female("Gita").
female("Pam").

female("Jenny").

female("Mina").

female("Sonia").

parent("Nita","Rohan").

parent("Gita","Rohan").

parent("Sonu","Rohan").

parent("Monu","Rohan").

parent("Nita","Rina").

parent("Gita","Rina").

parent("Sonu","Rina").

parent("Monu","Rina").

parent("Rosh","Numa").

parent("Posh","Numa").

parent("Rosh","Nita").

parent("Posh","Nita").

parent("Sam","Gautam").

parent("Pam","Gautam").

parent("Sam","Gita").

parent("Pam","Gita").

parent("","Sonu").

parent("","Sonia").

parent("John","Monu").

parent("Jenny","Monu").
parent("John","Mina").

parent("Jenny","Mina").

mother(X,Y):-

female(Y),

parent(X,Y).

brother(X,Y):-

male(Y),

father(X,Z),

father(Y,Z),X\=Y.

sister(X,Y):-

female(Y),

father(X,Z),

father(Y,Z),X\=Y.

grandfather(X,Y):-

male(Y),

parent(X,Z),

parent(Z,Y).

grandmother(X,Y):-

female(Y),

parent(X,Z),

parent(Z,Y).

uncle1(X,Y):-

male(Y),

parent(X,Z),
brother(Z,Y).

/*uncle(X,Y):-

uncle1(X,Y);

aunt1(X,Z),

mother(P,Z),

father(P,Y).*/

aunt1(X,Y):-

female(Y),

parent(X,Z),

sister(Z,Y).

/*aunt(X,Y):-

aunt1(X,Y);

uncle1(X,Z),

parent(P,Z),

mother(P,Y).*/

father(X,Y):-

male(Y),

parent(X,Y).

Goal:-

mother(X,Y).

OUTPUT
4. Write a program to check given element is in the list or not.

Clause:-

member(X,List):-

delete(X,List,_).

delete(X,[X|Tail],Tail).

delete(X,[Y|Tail1],[Y|Tail2]):-

delete(X,Tail1,Tail2).

Goal:- member(d,

[a,b,c,d]). OUTPUT
5. Write a program to find the largest number from the give list.

maxlist([A],A).

maxlist([A|LIST],MAX):-

maxlist(LIST,MAX0),

( A>=MAX0,MAX=A;

A<MAX0,MAX=MAX0).

Goal :-

maxlist([1,2,3],3).

Screenshot :-
Tutorial 9
Convert following Prolog predicates into Semantic Net:

Answer:
cat(tom).
cat(cat1).
mat(mat1).
sat_on(cat1,mat1).
bird(bird1).
caught(tom,bird1).
like(X,cream) :– cat(X).
mammal(X) :– cat(X).
has(X,fur) :– mammal(X).
animal(X) :– mammal(X).
animal(X) :– bird(X).
owns(john,tom).
is_coloured(tom,ginger).
Semantic Nets:
These are an alternative to predicate logic as a form of knowledge representation, the idea is that
we can store our knowledge in form of a graph with nodes representing object in the world and
arcs representing relationships between those objects.
For example:
2. Write a program to print the last element of the list.

Clause:-

traverse([]).

traverse([Head|Tail]):-

Tail=[],

write(Head),nl.

traverse([_|Tail]):-

traverse(Tail).

Goal:-

traverse([1,2,3,4]).
OUTPUT

3. Write a program to print the sum of the elements of the given list.

Clause:-

findsum(L):-

sum(L,Sum),

write("\nSum Of Given List : ",Sum).

sum([],0).

sum([X|Tail],Sum):-

sum(Tail,Temp),

Sum=Temp+X.
OUTPUT

Goal: findsum([1,2,3,4,5])

Sum Of Given List : 15

Yes

-------------------------------------

Goal: findsum([])

Sum Of Given List : 0

Yes

-------------------------------------

Goal: findsum([1,2,3,4,5,6,7,8,9,10])

Sum Of Given List : 55

Yes
Tutorial 10
Write the Conceptual Dependency for following statements:

Answer:
(a) John gives Mary a book

(b) John gave Mary the book yesterday

2. Write a programme for File.

clauses

//For reading.

main:-

open('house.txt',read,Str),

read_houses(Str,Houses),

close(Str),
write(Houses), nl.

read_houses(Stream,[]):-

at_end_of_stream(Stream).

read_houses(Stream,[X|L]):-

\+ at_end_of_stream(Stream),

read(Stream,X),

read_houses(Stream,L).

//For writing.

main:-

open('hogwarts.txt',write,Stream),

write(Stream,'Hogwarts'),nl(Stream),

close(Stream).

goal

go.

OUTPUT
3. Monkey Banana problem.

Code:-

Domains

predicates

can_reach(symbol,symbol)

close(symbol,symbol)

clever(symbol)

under(symbol,symbol)

claim(symbol,symbol)

tall(symbol)

in_room(symbol)

move(symbol,symbol,symbol)

clauses

in_room(monkey).

in_room(banana).

in_room(chair).

tall(chair).

clever(monkey).

move(monkey,chair,banana).

claim(monkey,chair).

can_reach(X,Y):-

close(X,Y),

clever(X).

close(X,Y):-
under(Z,Y),

tall(Z),

claim(X,Z).

under(Z,Y):-

in_room(Y),

in_room(Z),

in_room(X),

move(X,Z,Y).

goal

can_reach(monkey,banana).

OUTPUT

Das könnte Ihnen auch gefallen