0% found this document useful (0 votes)
217 views

Lab Manual: B.E. 6 Semester

The lab manual provides instructions for 14 artificial intelligence practical assignments to be completed using C++, Prolog, and other programming languages. The practicals include implementing games like tic-tac-toe and the 8 puzzle using techniques like minimax search, A* search, and breadth-first search. It also includes developing an expert system for medical diagnosis using Prolog.

Uploaded by

Dencey
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)
217 views

Lab Manual: B.E. 6 Semester

The lab manual provides instructions for 14 artificial intelligence practical assignments to be completed using C++, Prolog, and other programming languages. The practicals include implementing games like tic-tac-toe and the 8 puzzle using techniques like minimax search, A* search, and breadth-first search. It also includes developing an expert system for medical diagnosis using Prolog.

Uploaded by

Dencey
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/ 22

Lab Manual

ARTIFICIAL INTELLIGENCE
SUBJECT CODE: 3161608
B.E. 6th Semester

List of Practicals
Sr. No Practical Description
1 Write a program to implement Tic-Tac-Toe game problem

2 Write a program to implement Single Player Game (Using Heuristic Function)

3 Write a program to Implement A* Algorithm

4 To study Various features, format and variables of prolog.

5 To Study usage of rules in prolog.

6 To Study usage of input, output predicate in prolog.

7 To study fail and cut predicate in prolog.

8 To Study usage of recursion in prolog.

9 To Study usage of List in Prolog.

10 Write a Program to solve 8 puzzle problem using DFS (Depth First Search) in
Prolog.

11 Write a Program to solve Water jug problem using BFS(Breadth First Search) in
Prolog.

12 Write a Program to implement N-Queen problem in Prolog.

13 Write a program to solve travelling salesman problem using Prolog.

14 Develop a expert system for medical diagnosis of childhood diseases using


prolog.
Sr. Practical Description
No
1 Write a program to implement Tic-Tac-Toe game problem
Solution:
// A C++ Program to play tic-tac-toe

#include<bits/stdc++.h>
using namespace std;

#define COMPUTER 1
#define HUMAN 2

#define SIDE 3 // Length of the board

// Computer will move with 'O'


// and human with 'X'
#define COMPUTERMOVE 'O'
#define HUMANMOVE 'X'

// A function to show the current board status


void showBoard(char board[][SIDE])
{
printf("\n\n");

printf("\t\t\t %c | %c | %c \n", board[0][0],


board[0][1], board[0][2]);
printf("\t\t\t--------------\n");
printf("\t\t\t %c | %c | %c \n", board[1][0],
board[1][1], board[1][2]);
printf("\t\t\t--------------\n");
printf("\t\t\t %c | %c | %c \n\n", board[2][0],
board[2][1], board[2][2]);

return;
}

// A function to show the instructions


void showInstructions()
{
printf("\t\t\t Tic-Tac-Toe\n\n");
printf("Choose a cell numbered from 1 to 9 as below"
" and play\n\n");

printf("\t\t\t 1 | 2 | 3 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 4 | 5 | 6 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 7 | 8 | 9 \n\n");

printf("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n\n");

return;
}

// A function to initialise the game


void initialise(char board[][SIDE], int moves[])
{
// Initiate the random number generator so that
// the same configuration doesn't arises
srand(time(NULL));

// Initially the board is empty


for (int i=0; i<SIDE; i++)
{
for (int j=0; j<SIDE; j++)
board[i][j] = ' ';
}

// Fill the moves with numbers


for (int i=0; i<SIDE*SIDE; i++)
moves[i] = i;

// randomise the moves


random_shuffle(moves, moves + SIDE*SIDE);

return;
}

// A function to declare the winner of the game


void declareWinner(int whoseTurn)
{
if (whoseTurn == COMPUTER)
printf("COMPUTER has won\n");
else
printf("HUMAN has won\n");
return;
}

// A function that returns true if any of the row


// is crossed with the same player's move
bool rowCrossed(char board[][SIDE])
{
for (int i=0; i<SIDE; i++)
{
if (board[i][0] == board[i][1] &&
board[i][1] == board[i][2] &&
board[i][0] != ' ')
return (true);
}
return(false);
}

// A function that returns true if any of the column


// is crossed with the same player's move
bool columnCrossed(char board[][SIDE])
{
for (int i=0; i<SIDE; i++)
{
if (board[0][i] == board[1][i] &&
board[1][i] == board[2][i] &&
board[0][i] != ' ')
return (true);
}
return(false);
}

// A function that returns true if any of the diagonal


// is crossed with the same player's move
bool diagonalCrossed(char board[][SIDE])
{
if (board[0][0] == board[1][1] &&
board[1][1] == board[2][2] &&
board[0][0] != ' ')
return(true);

if (board[0][2] == board[1][1] &&


board[1][1] == board[2][0] &&
board[0][2] != ' ')
return(true);

return(false);
}

// A function that returns true if the game is over


// else it returns a false
bool gameOver(char board[][SIDE])
{
return(rowCrossed(board) || columnCrossed(board)
|| diagonalCrossed(board) );
}
// A function to play Tic-Tac-Toe
void playTicTacToe(int whoseTurn)
{
// A 3*3 Tic-Tac-Toe board for playing
char board[SIDE][SIDE];

int moves[SIDE*SIDE];

// Initialise the game


initialise(board, moves);

// Show the instructions before playing


showInstructions();

int moveIndex = 0, x, y;

// Keep playing till the game is over or it is a draw


while (gameOver(board) == false &&
moveIndex != SIDE*SIDE)
{
if (whoseTurn == COMPUTER)
{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = COMPUTERMOVE;
printf("COMPUTER has put a %c in cell %d\n",
COMPUTERMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = HUMAN;
}

else if (whoseTurn == HUMAN)


{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = HUMANMOVE;
printf ("HUMAN has put a %c in cell %d\n",
HUMANMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = COMPUTER;
}
}

// If the game has drawn


if (gameOver(board) == false &&
moveIndex == SIDE * SIDE)
printf("It's a draw\n");
else
{
// Toggling the user to declare the actual
// winner
if (whoseTurn == COMPUTER)
whoseTurn = HUMAN;
else if (whoseTurn == HUMAN)
whoseTurn = COMPUTER;

// Declare the winner


declareWinner(whoseTurn);
}
return;
}

// Driver program
int main()
{
// Let us play the game with COMPUTER starting first
playTicTacToe(COMPUTER);

return (0);
}

2 Write a program to implement Single Player Game (Using Heuristic Function)


Solution:
// C++ program to implement Best First Search using priority
// queue
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pi;

vector<vector<pi> > graph;

// Function for adding edges to graph


void addedge(int x, int y, int cost)
{
graph[x].push_back(make_pair(cost, y));
graph[y].push_back(make_pair(cost, x));
}

// Function For Implementing Best First Search


// Gives output path having lowest cost
void best_first_search(int source, int target, int n)
{
vector<bool> visited(n, false);
// MIN HEAP priority queue
priority_queue<pi, vector<pi>, greater<pi> > pq;
// sorting in pq gets done by first value of pair
pq.push(make_pair(0, source));
visited = true;

while (!pq.empty()) {
int x = pq.top().second;
// Displaying the path having lowest cost
cout << x << " ";
pq.pop();
if (x == target)
break;

for (int i = 0; i < graph[x].size(); i++) {


if (!visited[graph[x][i].second]) {
visited[graph[x][i].second] = true;
pq.push(graph[x][i]);
}
}
}
}

// Driver code to test above methods


int main()
{
// No. of Nodes
int v = 14;
graph.resize(v);

// The nodes shown in above example(by alphabets) are


// implemented using integers addedge(x,y,cost);
addedge(0, 1, 3);
addedge(0, 2, 6);
addedge(0, 3, 5);
addedge(1, 4, 9);
addedge(1, 5, 8);
addedge(2, 6, 12);
addedge(2, 7, 14);
addedge(3, 8, 7);
addedge(8, 9, 5);
addedge(8, 10, 6);
addedge(9, 11, 1);
addedge(9, 12, 10);
addedge(9, 13, 2);

int source = 0;
int target = 9;

// Function call
best_first_search(source, target, v);
return 0;
}
3 Write a program to Implement A* Algorithm.
Solution:
Student will able to get detailed Solution of A* algorithm implementation in following
link on problem 15 puzzle solver
https://rosettacode.org/wiki/A*_search_algorithm

4 To study Various features, format and variables of prolog.

WAP in prolog contains simple facts then compile and run it.
Solution:
symptom(chicken_pox,chills).
symptom(chicken_pox,high_fever).
symptom(flu,chills).
symptom(cold,mild_body_ache).
symptom(flu,severe_body_ache).
symptom(cold,runny_nose).
symptom(flu,runny_nose).
symptom(flu,moderate_cough).

Compile it in swi prolog editor.


Then run it using consult(prac1). or [prac1]
5 To Study usage of rules in prolog.

WAP in prolog to generate rules for family relation from given facts.

Solution:

male(harry).
female(liz).

parent(phil, chas).
parent(liz, chas).
parent(chas,harry).
parent(chas,wills).

grandmother(GM, C):-
mother(GM, P),
parent(P, C).

mother(M,C):-
female(M),
parent(M, C).

Create rules like above for another relation of family.


6 To Study usage of input, output predicate in prolog.
1) WAP in prolog which contains facts with username and password in it and then ask
user to
enter username and password and give appropriate output.

Solution:
logon:-
getinput(_,_),
write("You are log in"),nl.

logon:-
write("Sorry, Your username or password is wrong"),nl,
write("Please Try Again"),nl.

getinput(Username,Password):-
write("Enter your Username"),nl,
read(Username),nl,
write("Enter your Password"),nl,
read(Password),nl,
user(Username,Password).

user(hardik,maheta).
user(nishant,sanghani).
user(viral,parmar).

7 To study fail and cut predicate in prolog.


Solution:
location("Ahmedabad","Gujarat").
location("Mumbai","Maharashtra").
location("Bangaluru","Karnataka").

go:-
writef(" CITY "),writef(" STATE "),writef("\n"),
fail.
go:-
location(City,State),
/*checkstate(State),*/
writef(City),writef(State),writef("\n"),
fail.
go.

/*
checkstate("Maharashtra"):-
fail.
checkstate(_).
*/
8 To Study usage of recursion in prolog.

1) WAP in prolog to find factorial of given number.


Solution:
go:-
write("Enter the number for which you want to find factorail"),nl,
read(N),nl,
factorial(N,X),
write("The factorail of "),write(N),write(" is "),write(X),nl.
go:-
write("Your program is terminated becasuse you have entered negative number").

factorial(0,1).

factorial(N,F) :-
N > 0,
N1 is N-1,
factorial(N1,F1),
F is N * F1.
2) WAP in prolog to find Fibonacci series up to given number.
Solution:
go:-
write("Enter the number upto which you want to print fibonaci series"),nl,
read(N),nl,
write(0),nl,
write(1),nl,
fibonaci(0,1,N).

go.

fibonaci(A,B,N):-
C is A + B,
C < N,
write(C),nl,
fibonaci(B,C,N).

3) WAP in prolog to find GCD and LCM of two numbers.


Solution:
go:-
write("Enter the number 1"),nl,
read(N1),nl,
write("Enter the number 2"),nl,
read(N2),nl,
gcd(N1,N2,G),
write("The GCD is "),write(G),nl,
lcm(N1,N2,L),
write("The LCM is "),write(L),nl.

go.

gcd(X,Y,G):-
X = Y,
G=X.
gcd(X,Y,G):-
X < Y,
Y1 is Y-X,
gcd(X,Y1,G).
gcd(X,Y,G):-
X > Y,
gcd(Y,X,G).

lcm(X,Y,G):-
gcd(X,Y,GCD),
G is X * Y // GCD.

Write a program to add first N Numbers.


go:-
write("Enter the number for which you want to find Sum"),nl,
read(N),nl,
sum(N,X),
write("The Sum of first "),write(N),write("number is "),write(X),nl.
go.

sum(0,0).

sum(N,F) :-
N > 0,
N1 is N-1,
sum(N1,F1),
F is N + F1.

9 To Study usage of List in Prolog.

1) WAP in prolog to check whether the element is member of list.


Solution:
go:-
write("Enter your list in which you want to search"),nl,
read(L),nl,
write("Enter the member you want to search"),nl,
read(X),nl,
member(X,L),
write("Member found in list"),nl.

go:-
write("Member is not found in list").

member(X, [X|_]). % member(X, [Head|Tail]) is true if X = Head


% that is, if X is the head of the list
member(X, [_|Tail]) :- % or if X is a member of Tail,
member(X, Tail). % ie. if member(X, Tail) is true.memeber([Head|Tail],X,Y):-
2) WAP in prolog to find last and nth element in list.
Solution:
go:-
write("Enter your list"),nl,
read(L1),nl,
last_element(L1,X),
write("Last element is "),write(X),nl,
write("Enter Index "),nl,
read(N),nl,
n_element(L1,N,Y),
write(N),write(" th element is "),write(Y),nl.

last_element([Head],X):-
X=Head.
last_element([_|Tail],X):-
last_element(Tail,X).
last_element([],X):-
write("list is Empty").

n_element([Head|_],1,X):-
X=Head.

n_element([_|Tail],N,X):-
NN is N - 1,
n_element(Tail,NN,X).

n_element([],N,X):-
write("List is empty").
3) WAP in prolog to do intersection and union of two list.
Solution:
go:-
write("Enter your list 1"),nl,
read(L1),nl,
write("Enter your list 2"),nl,
read(L2),nl,
intersect(L1,L2,L3),
write("Intersection of two list is "),write(L3),nl,
union(L1,L2,L4),
write("Union of two list is "),write(L4),nl.

intersect([ ], X, [ ]).

intersect([X|R], Y, [X|Z]) :- member(X, Y), !, intersect(R, Y, Z).

intersect([X|R], Y, Z) :- intersect(R, Y, Z).

union([ ], X, X).

union([X|R], Y, Z):- member(X, Y), !, union(R, Y, Z).

union([X|R], Y, [X|Z]):- union(R, Y, Z).

member(X, [X|_]). % member(X, [Head|Tail]) is true if X = Head


% that is, if X is the head of the list
member(X, [_|Tail]) :- % or if X is a member of Tail,
member(X, Tail). % ie. if member(X, Tail) is true.memeber([Head|Tail],X,Y):-
4) Write a program in prolog to reverse the element in list.
Solution:
go:-
write("Enter your list"),nl,
read(L1),nl,
reverse_list(L1,L2),
write("Reverse list is"),write(L2),nl.

reverse_list(A,B):-
reverse(A,[],B).
reverse([],A,A).
reverse([Head|Tail],X,Y):-
reverse(Tail,[Head|X],Y).
10 Write a Program to solve 8 puzzle problem using A* heuristic search in Prolog.
Solution:
:-
object(eight_puzzle,
instantiates(heuristic_state_space)).
:- info([
version is 1.1,
author is 'Paulo Moura',
date is 2004/8/15,
comment is 'Eight puzzle heuristic state space search
problem.'
]).
:- uses(list, [member/2]).
initial_state(four_steps, [2/2,1/3,3/2,2/3,3/3,3/1,2/1,1/1,1/2])
initial_state(five_steps, [2/1,1/2,1/3,3/3,3/2,3/1,2/2,1/1,2/3])
initial_state(eighteen_steps, [2/2,2/3,1/3,3/1,1/2,2/1,3/3,1/1,3
goal_state(goal, [2/2,1/3,2/3,3/3,3/2,3/1,2/1,1/1,1/2]).
print_state([S0,S1,S2,S3,S4,S5,S6,S7,S8]) :-
member(Y, [3, 2, 1]),
nl,
member(X, [1, 2, 3]),
member(Tile-X/Y, [' '-S0,1-S1,2-S2,3-S3,4-S4,5-S5,
S6,7-S7,8-S8]),
write(Tile),
fail.
print_state(_) :-
nl.
next_state([Empty| L], [Tile| L2], 1) :-
swap(Empty, Tile, L, L2).
swap(Empty, Tile, [Tile| L], [Empty| L]) :-
dist(Empty, Tile, 1).
swap(Empty, Tile, [Tile2| L], [Tile2| L2]) :-
swap(Empty, Tile, L, L2).
dist(X/Y, X2/Y2, D) :-
abs_diff(X, X2, Dx),
abs_diff(Y, Y2, Dy),
D is Dx + Dy.
abs_diff(A, B, D) :-
A > B ->
D is A - B
;
D is B - A.
heuristic([_| L], H) :-
goal_state(_, [_| G]),
totdist(L, G, 0, D),
seq(L, S),
H is D + 3*S.
totdist([], [], D, D).
totdist([T| L], [T2| L2], Acc, D) :-
dist(T, T2, D1),
Acc2 is Acc + D1,
totdist(L, L2, Acc2, D).
seq([First| L], S) :-
seq([First| L], First, 0, S).
seq([T1, T2| L], First, Acc, S) :-
score(T1, T2, S1),
Acc2 is Acc + S1,
seq([T2| L], First, Acc2, S).
seq([Last], First, Acc, S) :-
score(Last, First, Score),
S is Acc + Score.
score(2/2, _, 1) :- !.
score(1/3, 2/3, 0) :- !.
score(2/3, 3/3, 0) :- !.
score(3/3, 3/2, 0) :- !.
score(3/2, 3/1, 0) :- !.
score(3/1, 2/1, 0) :- !.
score(2/1, 1/1, 0) :- !.
score(1/1, 1/2, 0) :- !.
score(1/2, 1/3, 0) :- !.
score(_, _, 2) :- !.
:- end_object.
11 Write a Program to solve Water jug problem using BFS (Breadth First Search) in Prolog.
Solution:

database
visited_state(integer,integer)

predicates

state(integer,integer)

clauses

state(2,0).

state(X,Y):- X < 4,
not(visited_state(4,Y)),
assert(visited_state(X,Y)),
write("Fill the 4-Gallon Jug: (",X,",",Y,") --> (", 4,",",Y,")\n"),
state(4,Y).
state(X,Y):- Y < 3,
not(visited_state(X,3)),
assert(visited_state(X,Y)),
write("Fill the 3-Gallon Jug: (", X,",",Y,") --> (", X,",",3,")\n"),
state(X,3).

state(X,Y):- X > 0,
not(visited_state(0,Y)),
assert(visited_state(X,Y)),
write("Empty the 4-Gallon jug on ground: (", X,",",Y,") --> (", 0,",",Y,")\n"),
state(0,Y).

state(X,Y):- Y > 0,
not(visited_state(X,0)),
assert(visited_state(X,0)),
write("Empty the 3-Gallon jug on ground: (", X,",",Y,") --> (", X,",",0,")\n"),
state(X,0).

state(X,Y):- X + Y >= 4,
Y > 0,
NEW_Y = Y - (4 - X),
not(visited_state(4,NEW_Y)),
assert(visited_state(X,Y)),
write("Pour water from 3-Gallon jug to 4-gallon until it is full: (", X,",",Y,") --> (",
4,",",NEW_Y,")\n"),
state(4,NEW_Y).

state(X,Y):- X + Y >=3,
X > 0,
NEW_X = X - (3 - Y),
not(visited_state(X,3)),
assert(visited_state(X,Y)),
write("Pour water from 4-Gallon jug to 3-gallon until it is full: (", X,",",Y,") --> (",
NEW_X,",",3,")\n"),
state(NEW_X,3).

state(X,Y):- X + Y <=4,
Y > 0,
NEW_X = X + Y,
not(visited_state(NEW_X,0)),
assert(visited_state(X,Y)),
write("Pour all the water from 3-Gallon jug to 4-gallon: (", X,",",Y,") --> (",
NEW_X,",",0,")\n"),
state(NEW_X,0).

state(X,Y):- X+Y<=3,
X > 0,
NEW_Y = X + Y,
not(visited_state(0,NEW_Y)),
assert(visited_state(X,Y)),
write("Pour all the water from 4-Gallon jug to 3-gallon: (", X,",",Y,") --> (",
0,",",NEW_Y,")\n"),
state(0,NEW_Y).

state(0,2):- not(visited_state(2,0)),
assert(visited_state(0,2)),
write("Pour 2 gallons from 3-Gallon jug to 4-gallon: (", 0,",",2,") --> (", 2,",",0,")\
n"),
state(2,0).

state(2,Y):- not(visited_state(0,Y)),
assert(visited_state(2,Y)),
write("Empty 2 gallons from 4-Gallon jug on the ground: (", 2,",",Y,") --> (",
0,",",Y,")\n"),
state(0,Y).

goal
makewindow(1,2,3,"4-3 Water Jug Problem",0,0,25,80),
state(0,0).

Output

+-----------------------------4-3 Water Jug Problem--------------------------+


¦Fill the 4-Gallon Jug: (0,0) --> (4,0) ¦
¦Fill the 3-Gallon Jug: (4,0) --> (4,3) ¦
¦Empty the 4-Gallon jug on ground: (4,3) --> (0,3) ¦
¦Pour all the water from 3-Gallon jug to 4-gallon: (0,3) --> (3,0) ¦
¦Fill the 3-Gallon Jug: (3,0) --> (3,3) ¦
¦Pour water from 3-Gallon jug to 4-gallon until it is full: (3,3) --> (4,2) ¦
¦Empty the 4-Gallon jug on ground: (4,2) --> (0,2) ¦
¦Pour all the water from 3-Gallon jug to 4-gallon: (0,2) --> (2,0) ¦
¦

12 Write a Program to implement N-Queen problem in Prolog.


Solution:
use_module(library(lists)).
/*
N-queens problem solved in Prolog (SWI-Prolog).
Usage es: n_queen(4,X).
*/

n_queen(N, Solution) :-
%create a list of N dummy variabiles
length(Solution, N),

queen(Solution, N). %search for a configuration of N queens


%returns a list of integer from K to N included es up2N(1,3,X) X = [1,2,3]
up2N(N,N,[N]) :-!.
up2N(K,N,[K|Tail]) :- K < N, K1 is K+1, up2N(K1, N, Tail).

queen([],_). %No queens is a solution for any N queens problem. All queens are in a safe
position.

queen([Q|Qlist],N) :-

queen(Qlist, N), %first we solve the subproblem

%we then generate all possible positions for queen Q


up2N(1,N,Candidate_positions_for_queenQ),

%we pick one of such position


member(Q, Candidate_positions_for_queenQ),

%we check whether the queen Q is safe


check_solution(Q,Qlist, 1).

check_solution(_,[], _).

check_solution(Q,[Q1|Qlist],Xdist) :-
Q =\= Q1, %not on the same row
Test is abs(Q1-Q),
Test =\= Xdist, %diagonal distance
Xdist1 is Xdist + 1,
check_solution(Q,Qlist,Xdist1).
13 Write a program to solve travelling salesman problem using Prolog.
Solution:
domains
/* will allow us cooperate with better names, for me this is like #typedef in C++ */
  town = symbol
  distance = unsigned
  rib = r(town,town,distance)
  tlist = town*
  rlist = rib*
predicates
  nondeterm way(town,town,rlist,distance)
  nondeterm route(town,town,rlist,tlist,distance)
  nondeterm route1(town,tlist,rlist,tlist,distance)
  nondeterm ribsmember(rib,rlist)
  nondeterm townsmember(town,tlist)
  nondeterm tsp(town,town,tlist,rlist,tlist,distance)
  nondeterm ham(town,town,tlist,rlist,tlist,distance)
  nondeterm shorterRouteExists(town,town,tlist,rlist,distance)
  nondeterm alltown(tlist,tlist)
  nondeterm write_list(tlist)
clauses
  /*
  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_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 = 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,“n“).
%   fail.
  
goal
/* EXAMPLE 1
  AllTowns = [a,b,c,d],
  AllWays = [r(a,b,1),r(a,c,10),r(c,b,2),r(b,c,2),r(b,d,5),r(c,d,3),r(d,a,4)],
*/
/* EXAMPLE 2 */
  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),
%SWITCH HERE
%  tsp(a,b,AllTowns,AllWays,Route,Distance),
  write(“Finally:n“),
  write_list(Route),
  write(” tMIN_D = “,Distance,“n“).

14 Develop a expert system for medical diagnosis of childhood diseases using prolog.
Solution:
domains
disease,indication,name = symbol

predicates
hypothesis(name,disease)
symptom(name,indication)

clauses
symptom(amit,fever).
symptom(amit,rash).
symptom(amit,headache).
symptom(amit,runn_nose).

symptom(kaushal,chills).
symptom(kaushal,fever).
symptom(kaushal,hedache).

symptom(dipen,runny_nose).
symptom(dipen,rash).
symptom(dipen,flu).

hypothesis(Patient,measels):-
symptom(Patient,fever),
symptom(Patient,cough),
symptom(Patient,conjunctivitis),
symptom(Patient,rash).

hypothesis(Patient,german_measles) :-
symptom(Patient,fever),
symptom(Patient,headache),
symptom(Patient,runny_nose),
symptom(Patient,rash).

hypothesis(Patient,flu) :-
symptom(Patient,fever),
symptom(Patient,headache),
symptom(Patient,body_ache),
symptom(Patient,chills).

hypothesis(Patient,common_cold) :-
symptom(Patient,headache),
symptom(Patient,sneezing),
symptom(Patient,sore_throat),
symptom(Patient,chills),
symptom(Patient,runny_nose).

hypothesis(Patient,mumps) :-
symptom(Patient,fever),
symptom(Patient,swollen_glands).
hypothesis(Patient,chicken_pox) :-
symptom(Patient,fever),
symptom(Patient,rash),
symptom(Patient,body_ache),
symptom(Patient,chills).

You might also like