Program No.1 Turbo Prolog Features and Format
Program No.1 Turbo Prolog Features and Format
1
Turbo Prolog features and format.
Prolog is a logic programming language associated with artificial intelligence and computational linguistics.
It has its roots in first order logic, a formal logic, and unlike many other programming languages. It is
intended primarily as a declarative programming language, the program logic is expressed in terms of
relations, represented as facts and rules.
The official version of Prolog was developed at the university of Marseilles, France by Alain Colmerauer in
the early 1970s as convenient tool for programming in logic.
Turbo Prolog is a typed Prolog compiler, which means that it is much faster than the interpreted Prolog.
Difference between Turbo Prolog and other programming languages:
1. Name and structures of objects involved in the problem.
2. Name of relation which are known to exist between the objects.
3. Facts and rules describing these relations.
Execution of Turbo Prolog programs is controlled automatically. When a Turbo Prolog program is executed,
the system tries to find all possible sets of values that satisfy the given goal. During execution , results may
be displayed or the user may be prompted to type in some data. turbo prolog use a backtracking mechanism
which, once one solution has been found ,causes Turbo Prolog to revaluate any assumption made to see if
some new variable values will provide new solutions.
Turbo Prolog is powerful. Turbo Prolog typically uses ten times fewer program lines when solving a problem
than language like Pascal.
Turbo Prolog has a built in pattern recognition facility, as well as simple and efficient way of handling
recursive structures.
2
A Prolog program consists of a number of clauses. each clause is either a fact or rule. After Prolog program is
loaded in a Prolog interpreter, user can submit goals or queries, a the Prolog interpreter will give results
according to the facts and rule.
Facts
A fact must start with a predicate and end with a full stop. The predicate may be followed by one or more
arguments which are enclosed by parentheses. The arguments can be atoms, numbers, variables or lists.
Arguments are separated by commas. In a Prolog program a presence of fact indicate that is true an absence
of a fact indicates a statement that is not true.
For example:- father(kishan, vishal)
Rules
Rule can be viewed as an extension of fact with added conditions that also have to be satisfied for it to be
true. It consists of two parts-the first part is similar to a fact and the second part consists of other clauses
which must all be true for the rule itself to be true. These two parts are separated by ":-".you may interpret
at this operator as "if" in English.
For example:-grandfather(X,Y):-father(X,Z),parent(Z,Y).
When a Prolog interpreter is running, you may probably see the prompt "?-" on the screen. This prompts the
user to enter a goal or query.
Goals
Goal is statement starting with a predicate and probably followed by its arguments. The purpose of
submitting a goal is to find out whether the statement represented by the goal is true according to the
knowledge database.in valid goal, the predicate must have appeared in at least one fact or rule in the
consulted program, and the number of arguments in the goal must be the same as that appears in the
consulted program. Also, all the arguments are constant.
Queries
A query is a statement starting with a predicate and followed by its arguments, some of which are variables.
Similar to goals, the predicate of a valid query must have appeared in at least one fact or rule in the
consulted program, and the number of arguments in the query must be same as that appears in the
consulted program. The purpose of submitting a query is to find values to substitute into the variables in the
query such that the query is satisfied.
3
Turbo Prolog program example:-
DOMAINS
name = string
person,activity = symbol
PREDICATES
is(person,name)
likes(person,activity)
CLAUSES
likes(kishan,soccer).
likes(rahul,nda).
likes(bharat,cp).
likes(kanu,cricket).
likes(aditya,X) if likes(kanu,X).
likes(Y,gaming) if is(Y,"name").
is(bharat,"name").
is(kishan,"name").
4
Output:
5
Program No.2
PREDICATES
teaches(teacher,subject)
subcode(subject,code)
tcode(teacher,code)
CLAUSES
subcode(os,9).
subcode(c,10).
subcode(webd,5).
subcode(cg,1).
tcode(ds,10).
tcode(ab,4).
tcode(pp,1).
teaches(X,Y) if subcode(Y,A),tcode(X,B),A<=B.
6
Output:
7
Program No.3
Write a program for using Input, Output and fail predicates in Prolog.
PREDICATES
hello
GOAL
hello.
CLAUSES
hello:-
makewindow(1,7,7,"MY FIRST PROGRAM",4,56,10,22),
nl,write(" ENTER YOUR NAME "),
cursor(4,5),
readln(Name),nl,
write( "WELCOME " ,Name," !").
8
Output:
9
Program No.4
GOAL
hello.
CLAUSES
hello:-
10
Output:
11
Program No.5
PREDICATES
factorial(n,f)
go
GOAL
go.
CLAUSES
factorial(1,1) if !.
factorial(N,Res) if
N1 = N-1 and
factorial(N1,Between) and
Res = N*Between.
go:-
write("Enter the number "),
readreal(X),nl,
factorial(X,Y),
write("Factorial of ",X),
write(" is ",Y).
12
Output:
13
II. Using Fail predicate
DOMAINS
name = symbol
PREDICATES
father(name,name)
everybody
GOAL
everybody.
CLAUSES
father(kartik,amar).
father(aman,rahul).
father(aman,mohan).
everybody if
father(X,Y) and
write(X," is ",Y,"'s father. \n") and fail.
14
Output:
15
III. Using Not predicate
DOMAINS
person = symbol
PREDICATES
male(person)
smoker(person)
vegetarian(person)
is_healthy(person)
GOAL
is_healthy(X) and
write("A possible Healthy Male is ",X),nl.
CLAUSES
male(bharat).
male(kishan).
male(rahul).
smoker(op).
smoker(rahul).
vegetarian(bharat).
vegetarian(rahul).
is_healthy(X) if male(X) and not(smoker(X)).
is_healthy(X) if male(X) and vegetarian(X).
16
Output:
17
Program No.6
PREDICATES
factorial(n,f)
go
GOAL
go.
CLAUSES
factorial(1,1).
factorial(N,Res) if
N > 0 and
N1 = N-1 and
factorial(N1,FacN1) and
Res = N*FacN1.
go:-
write("Enter the number"),nl,
readreal(X),
factorial(X,Y),
write("The factorial of ",X),
write(" is ",Y).
18
Output:
19
Program No.7
int n;
int adj[MAX][MAX];
int state[MAX];
void create_graph();
void BF_Traversal();
void BFS(int v);
int main()
{
create_graph();
BF_Traversal();
return 0;
}
void BF_Traversal()
{
int v;
for(v=0; v<n; v++)
state[v] = initial;
printf("Enter Start Vertex for BFS: \n");
scanf("%d", &v);
BFS(v);
}
void BFS(int v)
{
int i;
insert_queue(v);
state[v] = waiting;
while(!isEmpty_queue())
20
{
v = delete_queue( );
printf("%d ",v);
state[v] = visited;
for(i=0; i<n; i++)
{
if(adj[v][i] == 1 && state[i] == initial)
{
insert_queue(i);
state[i] = waiting;
}
}
}
printf("\n");
}
int isEmpty_queue()
{
if(front == -1 || front > rear)
return 1;
else
return 0;
}
int delete_queue()
{
int delete_item;
if(front == -1 || front > rear)
{
printf("Queue Underflow\n");
exit(1);
}
delete_item = queue[front];
21
front = front+1;
return delete_item;
}
void create_graph()
{
int count,max_edge,origin,destin;
printf("Enter number of vertices : ");
scanf("%d",&n);
printf("Enter number of edges:");
scanf("%d",&max_edge);
printf("Note: GRAPH SHOULD BE CONNECTED\n");
printf("The edge name starts from '0' and goes to 'n-1'\n");
printf("For example\nEnter an edge(u,v):0 1 connects first and second node\nEnter an edge(u,v):0 n-1
connects first and last node\n");
22
Output:
23
II. Depth First Search
#include<stdio.h>
#include<stdlib.h>
node *G[20];
//heads of linked list
int visited[20];
int n;
void read_graph();
//create adjacency list
void insert(int,int);
//insert an edge (vi,vj) in te adjacency list
void DFS(int);
void main()
{
int i;
read_graph();
//initialised visited to 0
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
}
void DFS(int i)
{
node *p;
printf("\n%d",i);
p=G[i];
visited[i]=1;
while(p!=NULL)
{
i=p->vertex;
if(!visited[i])
DFS(i);
p=p->next;
}
}
void read_graph()
{
24
int i,vi,vj,no_of_edges;
printf("Enter number of vertices:");
scanf("%d",&n);
//initialise G[] with a null
for(i=0;i<n;i++)
{
G[i]=NULL;
//read edges and insert them in G[]
printf("Enter number of edges:");
scanf("%d",&no_of_edges);
printf("Note: GRAPH SHOULD BE CONNECTED");
printf("The edge name starts from '0' and goes to 'n-1'\n");
printf("For example\nEnter an edge(u,v):0 1 connects first and second node\n
Enter an edge(u,v):0 n-1 connects first and last node\n");
for(i=0;i<no_of_edges;i++)
{
printf("Enter an edge(u,v):");
scanf("%d%d",&vi,&vj);
insert(vi,vj);
}
}
printf("\n");
}
25
Output:
26
Program No.8
def neighbors(self,n):
for n1, d in self.nodes[n]:
yield n1
def distance_between(self,n1, n2):
for n, d in self.nodes[n1]:
if n == n2:
return d
def heuristic_cost_estimate(self,n, goal):
return 1
print("The graph is :")
print(" A")
print(" / \ ")
print(" 100 / \ 20")
print(" / \ ")
print(" B C ")
print(" \\\ / ")
print(" 20 \\\ / 20 ")
print(" \\\ / ")
print(" D")
start_node = input("Enter the start node for searching : ").upper()
end_node = input("Enter the end node for searching : ").upper()
Obj_Path_finder = Path_finder()
path = list(Obj_Path_finder.astar(start_node,end_node))
for i in path:
print(i,end="")
if i == end_node:
print("->"+start_node)
break
print("->",end="")
27
Output:
28
Program No.9
30
Output:
31
Program No.10
int ary[10][10],completed[10],n,cost=0;
void takeInput()
{
int i,j;
cout<<"Enter the number of Places: ";
cin>>n;
cout<<"\nEnter the Cost Matrix\n";
cout<<"Note: It's an adjacency matrix with each value representing distance\n";
for(i=0;i < n;i++)
{
cout<<"\nEnter Elements of Row: "<<i+1<<"\n";
for( j=0;j < n;j++)
cin>>ary[i][j];
completed[i]=0;
}
cout<<"\n\nThe cost list is:";
for( i=0;i < n;i++)
{
cout<<"\n";
for(j=0;j < n;j++)
cout<<"\t"<<ary[i][j];
}
}
int least(int c)
{
int i,nc=999;
int min=999,kmin;
for(i=0;i < n;i++)
{
if((ary[c][i]!=0)&&(completed[i]==0))
if(ary[c][i]+ary[i][c] < min)
{
min=ary[i][0]+ary[c][i];
kmin=ary[c][i];
nc=i;
}
}
if(min!=999)
cost+=kmin;
32
return nc;
}
int main()
{
takeInput();
cout<<"\n\nThe Path is:\n";
mincost(0); //passing 0 because starting vertex
cout<<"\n\nMinimum cost is "<<cost;
return 0;
}
33
Output:
34