0% found this document useful (0 votes)
61 views22 pages

Ai FINAL

The document describes implementing the A* search algorithm in Prolog. It first provides an overview of the A* algorithm, explaining how it finds the shortest path between nodes in a graph by considering both cost to reach a node and estimated cost to the goal. It then gives a numerical example of using A* to find the shortest path on a grid, walking through the steps of the algorithm and demonstrating how to reconstruct the full path. Finally, it suggests implementing this example in Prolog code.

Uploaded by

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

Ai FINAL

The document describes implementing the A* search algorithm in Prolog. It first provides an overview of the A* algorithm, explaining how it finds the shortest path between nodes in a graph by considering both cost to reach a node and estimated cost to the goal. It then gives a numerical example of using A* to find the shortest path on a grid, walking through the steps of the algorithm and demonstrating how to reconstruct the full path. Finally, it suggests implementing this example in Prolog code.

Uploaded by

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

EXPERIMENT 2

AIM :- Introduction to Prolog.

PROLOG-PROGRAMMING IN LOGIC
PROLOG stands for Programming, In Logic - 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 demonstration) and Alian Colmerauer at
Marseilles (implementation). David D.II. Warren's efficient implementation at
Edinburgh in the mid-1970's greatly contributed to the popularity of PROLOG.
PROLOG is a programming language centred around a small set of basic
mechanisms, including pattern matching, tree based data structuring and
automatic backtracking. This Small set constitutes a surprisingly powerful and
flexible programming framework. PROLOG is especially well suited for
problems that involve objects- in particular, structured objects and relations
between them.
SYMBOLIC LANGUAGE
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 consistency with
respect to the general rule. Features like this make PROLOG a powerful
language for Artificial LanguageA1.) 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 on one page.
FACTS, RULES, AND QUERIES
Programming in PROIOG is accomplished by creating 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 resolution. FOR
EXAMPLE:

FACTS:
Some facts about family relationships could be written as:
sister( sue,bill)
parent( ann sam)
male (jo)
female(riya)

RULES:
To represent the general rule for grandfather, we write:
grand father( X2)
parent (X,Y)
parent(Y,Z)
male(X)

QUERIES:
Given a database of facts and rules such as that above, we may make queries
by typing after a query a symbol’?’ statements such as:
?-parent(X,sam) Xann
?grandfather(X,Y)
X=jo, Y=sam
PROLOG IN DESIGNING EXPERT SYSTEMS
An expert system is a set of programs that manipulates encoded knowledge to
solve problems in a specialized domain that normally requires human
expertise. An expert system's knowledge is obtained from expert sources such
as texts, journal articles, databases etc and encoded in a form suitable for the
system to use in its inference or reasoning processes. Once a sufficient body of
expert knowledge has been acquired, it must be encoded in some form, loaded
into knowledge base, then tested, and refined continually throughout the life
of the system PROLOG serves as a powerful language in designing expert
systems because of its following features.
• Use of knowledge rather than data
• Modification of the knowledge base without recompilation of the control
programs.
• Capable of explaining conclusion.
• Symbolic computations resembling manipulations of natural language.
• Reason with meta-knowledge.
META PROGRAMMING
A meta-program is a program that takes other programs as data. Interpreters
and compilers are examples of mela-programs. Meta-interpreter is a particular
kind of meta-program: an interpreter for a language written in that language.
So a PROLOG interpreter is an interpreter for PROLOG, itself written in
PROLOG. Due to its symbol- manipulation capabilities. PROLOG is a powerful
language for meta-programming. Therefore, it is often used as an
implementation language for other languages. PROLOG is particularly suitable
as a language for rapid prototyping where we are interested in implementing
new ideas quickly. New ideas are rapidly implemented and experimented with.

Conclusion:
Thus, we have studied about prolog and its working environment.
EXPERIMENT 3

AIM:- Write a program in Prolog using clauses

Input:

Output:

Conclusion:Thus, we have implemented a prolog program using clauses.


Experiment 4

Aim: Write a program to solve the Monkey Banana problem.

Problem Statement:
1. A hungry monkey is in the room and he is near the door the monkey is on
the floor bananas have been hung from the centre of the ceiling of the room.
2. There is a chair present in the room near the window.
3. The monkey wants to eat bananas but he can't reach them.
4. How can monkey reach to the bananas?
Input:

Output:

Conclusion: Thus, we have implemented a program to solve the Monkey


Banana problem in prolog
Experiment 5
Aim:- Write a program to solve the Water Jug Problem

Code+Output:-
Conclusion:-
Thus, we have implemented a program to solve the Water jug problem in
python.
Experiment-6
Aim:- Write a program to implement A* Search Algorithm.
Theory:- The A* search algorithm is a widely used heuristic search algorithm in
computer science, particularly in pathfinding and graph traversal problems. It
efficiently finds the shortest path between nodes in a graph, taking into
account both the cost of reaching a node and the estimated cost to reach the
goal from that node. A* evaluates nodes by combining the cost to reach the
node from the start (known as g-score) and the estimated cost to reach the
goal from the node (known as h-score), and selects the node with the lowest f-
score (f = g + h) for expansion. This process continues until the goal is reached
or no more nodes are left to explore. A* guarantees finding the optimal
solution if certain conditions are met, such as having admissible heuristics (h)
that never overestimate the true cost to reach the goal.
Algorithm:- 1. Initialize:
- Create an open list of nodes to be evaluated. This starts with the initial node.
- Create a closed list to keep track of nodes that have been evaluated.
2. Evaluate Nodes:
- While the open list is not empty, repeat the following steps:
-Select the node with the lowest f-score (f = g + h) from the open list. This node
will be the current node for evaluation.
- Move the current node from the open list to the closed list.
3. Goal Check:
- If the current node is the goal node, the algorithm terminates and returns the
path from the initial node to the goal node.
4. Expand Nodes:
- Generate the successors (neighbors) of the current node.
- For each successor:
- If the successor is already in the closed list, skip it.
- If the successor is not in the open list, calculate its g-score (cost to reach from
the initial node) and h-score (estimated cost to reach the goal).
- If the successor is already in the open list and its new g-score is lower than
the previous one, update its g-score and parent node.
5. Repeat:
- Go back to step 2 until a goal node is found or the open list is empty.
6. Path Reconstruction:
- If a goal node is found, reconstruct the path from the initial node to the goal
node using the parent pointers stored during the search.
This algorithm efficiently explores the search space by prioritizing nodes that
are closer to the goal based on the heuristic function while ensuring
completeness and optimality under certain conditions, such as having
admissible heuristics.
Numerical:- Let's consider a simple example of finding the shortest path on a grid from a
start point to a goal point. In this example, we'll use the Manhattan distance heuristic, where
the heuristic estimate from a node to the goal is the sum of the absolute differences in their
x and y coordinates.

Let's go through the A* search algorithm step by step with the provided
example:

1. Initialization:
- We start with the open set containing only the start node `(0, 0)`.
- We initialize the `came_from`, `g_score`, `h_score`, and `f_score` dictionaries.
- `g_score` holds the cost from the start node to each node.
- `h_score` holds the heuristic estimate from each node to the goal node.
- `f_score` is the sum of `g_score` and `h_score`.
2. Main Loop:
- We select the node with the lowest `f_score` from the open set, which is `(0,
0)` in this case.
3. Goal Check:
- Since the current node `(0, 0)` is not the goal node `(4, 4)`, we proceed to
expand it.
4. Expand Nodes:
- We check the neighbors of `(0, 0)`.
- We ignore any neighbors outside the grid or blocked by obstacles.
- The valid neighbors are `(1, 0)` and `(0, 1)`.
5. Update Scores:
- For each valid neighbor, we calculate its tentative `g_score`, `h_score`, and
`f_score`.
- For `(1, 0)`, the `g_score` is 1 (as it's 1 step away from the start), and the
`h_score` is 7 (Manhattan distance to the goal).
- For `(0, 1)`, the `g_score` is also 1, and the `h_score` is 7.
- We update the scores and add the valid neighbors to the open set.
6. Repeat:
- We continue this process until the goal node `(4, 4)` is reached.
7. Path Reconstruction:
- Once the goal node is reached, we reconstruct the path from the start node
to the goal node using the `came_from` dictionary.

Let's implement this


# Let's define the heuristic function
def heuristic(node, goal):
return abs(node[0] - goal[0]) + abs(node[1] - goal[1])
# Let's define the reconstruction function
def reconstruct_path(came_from, current):
total_path = [current]
while current in came_from.keys():
current = came_from[current]
total_path.append(current)
return total_path[::-1]

# Let's define the A* search function


def a_star_search(grid, start, goal):
open_set = {start}
came_from = {}
g_score = {start: 0}
h_score = {start: heuristic(start, goal)}
f_score = {start: h_score[start]}

while open_set:
current = min(open_set, key=lambda node: f_score[node])
if current == goal:
return reconstruct_path(came_from, current)

open_set.remove(current)
for neighbor in [(current[0]+1, current[1]), (current[0]-1, current[1]),
(current[0], current[1]+1), (current[0], current[1]-1)]:
if neighbor[0] < 0 or neighbor[0] >= len(grid) or \
neighbor[1] < 0 or neighbor[1] >= len(grid[0]) or \
grid[neighbor[0]][neighbor[1]] == 1:
continue

tentative_g_score = g_score[current] + 1
if neighbor not in g_score or tentative_g_score < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
h_score[neighbor] = heuristic(neighbor, goal)
f_score[neighbor] = g_score[neighbor] + h_score[neighbor]
if neighbor not in open_set:
open_set.add(neighbor)

return []

# Let's define the grid


grid = [[0, 0, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]]

# Let's define the start and goal nodes


start = (0, 0)
goal = (4, 4)
# Let's find the shortest path using A* search
path = a_star_search(grid, start, goal)
print("Shortest path:", path)

Code+Output:-
Conclusion:-
Thus, we have implemented a program to solve A* search in python.
Experiment 7
Aim:- To implement Tic Tac Toe using BFS using Python
Code+Output:-
Conclusion:- Thus, we have implemented Tic Tac Toe game using BFS.
Experiment 8
Aim:- To solve N- Queen Problem
Code+Output:-
Conclusion:- Thus, we have solved N-Queens problem.
Index

Sr.No. Title Date Sign


USHA MITTAL INSTITUTE OF TECHNOLOGY
SNDT WOMEN’S UNIVERSITY
MUMBAI-400049

ARTIFICIAL INTELLIGENCE
LAB JOURNAL
2023-24

NAME:- PRATIKSHA SURESH MANWATKAR


SAAKSHI RAKESH JAGTAP

BRANCH:- COMPUTER ENGINEERING


YEAR:- 3RD YEAR
ROLL NO:- 35

You might also like