Artificial Intelligence (3161608) : B.E. Semester 6 (Information Technology)
Artificial Intelligence (3161608) : B.E. Semester 6 (Information Technology)
Artificial Intelligence (3161608) : B.E. Semester 6 (Information Technology)
Artificial Intelligence
(3161608)
B.E. Semester 6
(Information Technology)
Certificate
Place: __________
Date: __________
DTE’s Vision
Institute’s Vision
Institute’s Mission
Department’s Mission
Preface
Main motto of any laboratory/practical/field work is for enhancing required skills as well as
creating ability amongst students to solve real time problem by developing relevant
competencies in psychomotor domain. By keeping in view, GTU has designed competency
focused outcome-based curriculum for engineering degree programs where sufficient weightage
is given to practical work. It shows importance of enhancement of skills amongst the students
and it pays attention to utilize every second of time allotted for practical amongst students,
instructors and faculty members to achieve relevant outcomes by performing the experiments
rather than having merely study type experiments. It is must for effective implementation of
competency focused outcome-based curriculum that every practical is keenly designed to serve
as a tool to develop and enhance relevant competency required by the various industry among
every student. These psychomotor skills are very difficult to develop through traditional chalk
and board content delivery method in the classroom. Accordingly, this lab manual is designed
to focus on the industry defined relevant outcomes, rather than old practice of conducting
practical to prove concept and theory.
By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which creates an interest and students can have basic idea prior to
performance. This in turn enhances pre-determined outcomes amongst students. Each
experiment in this manual begins with competency, industry relevant skills, course outcomes as
well as practical outcomes (objectives). The students will also achieve safety and necessary
precautions to be taken while performing practical.
This manual also provides guidelines to faculty members to facilitate student centric lab
activities through each experiment by arranging and managing necessary resources in order that
the students follow the procedures with required safety and necessary precautions to achieve the
outcomes. It also gives an idea that how students will be assessed by providing rubrics.
Artificial Intelligence (AI) has become an integral part of many industries and fields, impacting
human life in numerous ways. AI techniques, such as Predicate Logic, Production Rules, and
Semantic Networks, are used to encode knowledge in computer systems and solve real-world
problems. Additionally, fields of AI like Game Playing, Natural Language Processing, and
Connectionist Models play a vital role in various industries. It is essential for students to learn
programming languages for AI as it is used in both technical and non-technical fields. AI has
been implemented in every branch of engineering, making systems more effective and dynamic.
The Fundamentals of Artificial Intelligence course aims to provide exposure to the basic AI
techniques.
Utmost care has been taken while preparing this lab manual however always there is chances of
improvement. Therefore, we welcome constructive suggestions for improvement and removal
of errors if any.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Sr.
Objective(s) of Experiment CO1 CO2 CO3 CO4
No.
A. Write a prolog program to put facts
indicating that sachin likes cricket, saurav likes
cricket, raj likes football, karan likes basketball,
indra likes chess and add rule that parth likes
whatever saurav likes. Write goal for following
queries:
a. Find the name of all players who like
cricket.
b. Check whether raj likes cricket or not.
c. Display the list of all players with the
1. √
game they like.
d. Display the name of players who likes
any game except cricket.
B. Implement prolog program that asks
username and password from user and display
whether login is successful or not according to
knowledge base considered in the program.
a. Perform above program without
recursion.
b. Perform above program with recursion.
Implement following prolog programs.:
a. To find the greatest variable among the
three variables.
b. To find a factorial of a given number. √
2.
c. To check whether a given number is
palindrome or not.
d. To check whether a given number is prime
or not.
Solve 8 Puzzle Problem using A* Algorithm in any
3. programming Language. √
1. Teacher should provide the guideline with demonstration of practical to the students
with all features.
2. Teacher shall explain basic concepts/theory related to the experiment to the students
before starting of each practical
3. Involve all the students in performance of each experiment.
4. Teacher is expected to share the skills and competencies to be developed in the
students and ensure that the respective skills and competencies are developed in the
students after the completion of the experimentation.
5. Teachers should give opportunity to students for hands-on experience after the
demonstration.
6. Teacher may provide additional knowledge and skills to the students even though not
covered in the manual but are expected from the students by concerned industry.
7. Give practical assignment and assess the performance of students based on task
assigned to check whether it is as per the instructions or not.
8. Teacher is expected to refer complete curriculum of the course and follow the
guidelines for implementation.
1. Students are expected to carefully listen to all the theory classes delivered by the faculty
members and understand the COs, content of the course, teaching and examination
scheme, skill set to be developed etc.
2. Students will have to perform experiments as per practical list given.
3. Students have to show output of each program in their practical file.
4. Students are instructed to submit practical list as per given sample list shown on next page.
5. Student should develop a habit of submitting the experimentation work as per the schedule
and s/he should be well prepared for the same.
Index
(Progressive Assessment Sheet)
Sr. Objective(s) of Experiment Page Date of Date of Assessme Sign. of Remar
No. No. perform submiss nt Teacher ks
ance ion Marks with date
A. Write a prolog program to put facts
indicating that sachin likes cricket, saurav
likes cricket, raj likes football, karan likes
basketball, indra likes chess and add rule
that parth likes whatever saurav likes.
Write goal for following queries:
a. Find the name of all players who
like cricket.
b. Check whether raj likes cricket or
not.
c. Display the list of all players with
1. the game they like.
d. Display the name of players who
likes any game except cricket.
B. Implement prolog program that asks
username and password from user and
display whether login is successful or not
according to knowledge base considered
in the program.
a. Perform above program without
recursion.
b. Perform above program with
recursion.
Implement following prolog programs.:
a. To find the greatest variable among
the three variables.
b. To find a factorial of a given number.
2.
c. To check whether a given number is
palindrome or not.
d. To check whether a given number is
prime or not.
Solve 8 Puzzle Problem using A* Algorithm in
3. any programming Language.
Experiment No: 1
A. Write a prolog program to put facts indicating that sachin likes cricket, saurav likes cricket, raj
likes football, karan likes basketball, indra likes chess and add rule that parth likes whatever
saurav likes. Write goal for following queries:
a. Find the name of all players who like cricket.
b. Check whether raj likes cricket or not.
c. Display the list of all players with the game they like.
d. Display the name of players who likes any game except cricket.
B. Implement prolog program that asks username and password from user and display whether
login is successful or not according to knowledge base considered in the program.
a. Perform above program without recursion.
b. Perform above program with recursion.
Date:
Competency and Practical Skills: Basic Understanding of Predicated and Prolog Syntax
Theory:
There are only three basic constructs in Prolog: facts, rules, and queries. A collection of facts and
rules is called a knowledge base (or a database) and Prolog programming is all about writing
knowledge bases. That is, Prolog programs simply are knowledge bases, collections of facts and
rules which describe some collection of relationships that we find interesting.
Knowledge Base 1
Knowledge Base 1 (KB1) is simply a collection of facts. Facts are used to state things that are
unconditionally true of some situation of interest. For example, we can state that Mia, Jody, and
Yolanda are women, that Jody plays air guitar, and that a party is taking place, using the following
five facts:
woman(mia).
woman (jody).
woman (yolanda).
playsAirGuitar(jody).
party.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
?- woman (mia).
Prolog will answer
yes
Knowledge Base 2
happy (yolanda).
listens 2Music(mia).
listens 2Music(yolanda): - happy (yolanda). playsAirGuitar(mia):- listens2Music(mia).
playsAirGuitar(yolanda):- listens 2Music(yolanda).
There are two facts in KB2, listens2Music(mia) and happy(yolanda). The last three items it
contains are rules.
Rules state information that is conditionally true of the situation of interest The part on the left
hand side of the: - is called the head of the rule, the part on the right hand side is called the body.
So in general rules say: if the body of the rule is true, then the head of the rule is true too. And
now for the key point:
If a knowledge base contains a rule head - body, and Prolog knows that body follows from the
information in the knowledge base, then Prolog can infer head. This fundamental deduction step is
called modus ponens.
Knowledge Base 3
Knowledge Base 4
There are no rules, only a collection of facts. we're going to make use of variables. Here's an
example:
?- woman(X).
Prolog answers this query by working its way through KB4, from top to bottom, trying to unify
(or match) the expression woman(X) with the information KB4 contains. Now the first item in the
knowledge base is woman(mia). So, Prolog unifies X with mia, thus making the query agree
perfectly with this first item. (Incidentally, there's a lot of different terminology for this process:
we can also say that Prolog instantiates X to mia, or that it binds X to mia .) Prolog then reports
back to us as follows:
X = mia
That is, it not only says that there is information about at least one woman in KB4, it actually tells
us who she is. It didn't just say yes, it actually gave us the variable binding (or variable
instantiation) that led to success.
Knowledge Base 5
person(john).
person(susan).
person(bob).
person(alice).
city(new_york).
city(london).
city(paris).
city(tokyo).
lives_in(john, new_york).
lives_in(susan, london).
lives_in(bob, paris).
lives_in(alice, tokyo).
likes(john, sushi).
likes(john, pizza).
likes(susan, pizza).
likes(bob, croissants).
likes(alice, sushi).
likes_same_food(X, Y) :-
likes(X, Z),
likes(Y, Z),
X \= Y.
In this example, we have defined a knowledge base that includes facts about people and cities, as
well as rules that define relationships between them. Specifically, we have defined the following:
Four facts that define the people in our knowledge base (john, susan, bob, and alice) and
the cities they live in (new_york, london, paris, and tokyo).
Five facts that define the food preferences of our people.
A rule called likes_same_food/2 that defines a relationship between two people who like
the same food.
To use this knowledge base, we can query it using Prolog's built-in ?- operator. For example, we
can ask:
Artificial Intelligence (3170716) Enrollment Number: 21060116087
?- likes(john, sushi).
true.
This will return true, indicating that John likes sushi.
Procedure:
1. Define the domain of the knowledge base.
2. Define the facts.
3. Define the rules.
4. Test the knowledge base.
Observation/Program:
Code: (A)
% Facts
likes(sachin, cricket). % sachin likes cricket
likes(saurav, cricket). % saurav likes cricket
likes(raj, football). % raj likes football
likes(karan, basketball). % karan likes basketball
likes(indra, chess). % indra likes chess
% Rules
likes(parth, X) :- likes(saurav, X). % parth likes whatever saurav likes
Code: (B)
(a)% knowledge base
login(srijyaa, 123).
login(ayushi, 456).
login(abc, 123).
login(xyz, 456).
start:-
write('Enter Username: '), read(Username),
write('Enter Password: '), read(Password),
login(Username, Password), write('Login Successful').
start:-
write('Login Unsuccessful')
(b)
% knowledge base
login(srijyaa, 123). login(ayushi, 456).
login(abc, 123).
login(xyz, 456).
start:-
write('Enter Username: '), read(Username),
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Conclusion:
Prolog is a useful tool for implementing knowledge bases for various domains, including family
relationships, and can provide efficient and effective reasoning capabilities for querying and
analyzing such data.)
Quiz:
4. What are the different types of knowledge bases in Prolog and how are they
implemented?
Dynamic Knowledge Base
Static Knowledge Base
5. How do you query a Prolog knowledge base and what is the output?
In Prolog, you can query a knowledge base to retrieve information or to check whether
certain relationships hold true according to the defined facts and rules. Queries are posed
as goals, and Prolog attempts to find solutions that satisfy these goals based on the
knowledge provided.
6. What are the advantages and disadvantages of using Prolog for implementing
knowledge bases?
Advantages:
Declarative Syntax: Prolog's syntax is declarative, making it well-suited for
representing knowledge in a natural and intuitive way. This makes it easier to
express complex relationships and rules within the knowledge base.
Pattern Matching and Backtracking: Prolog's pattern matching and automatic
backtracking capabilities allow for efficient search and inference over the
knowledge base. This makes it suitable for tasks such as automated reasoning
and problem solving.
Disadvantages:
Suggested Reference:
1. http://lpn.swi-prolog.org/lpnpage.php?pageid=online
Problem Completeness
Knowledge Logic
Recognition and accuracy Ethics (2)
Rubrics (2) Building (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Experiment No: 2
Date:
Objectives:To create a functional and efficient Prolog program for solving logic puzzles.
Theory:
In Prolog, a program consists of a set of facts and rules that define relationships and properties in
a knowledge base. The primary theoretical foundation of Prolog is based on formal logic,
specifically first-order logic. Here's a brief overview of the key theoretical concepts that underlie
Prolog programs:
1. Predicates:
In Prolog, predicates are used to represent relationships or properties in the form of clauses.
Predicates consist of a name (an atom) and a fixed number of arguments. For example, `parent(X,
Y)` represents the "parent" relationship with two arguments, X and Y.
2. Facts:
Facts are the basic building blocks of Prolog programs. They represent simple, unconditionally
true statements. For example:
```
parent(john, mary) ```
3. Rules:
Rules define relationships and properties based on the satisfaction of certain conditions. Rules
have a head and a body. The head specifies the predicate to be derived, and the body specifies the
conditions that must be satisfied for the rule to apply. For example:
```
grandparent(X, Y) :- parent(X, Z), parent(Z, Y).
```
In this rule, `grandparent(X, Y)` is derived if `parent(X, Z)` and `parent(Z, Y)` are satisfied.
4. Logical Inference:
Prolog uses logical inference to make queries and derive conclusions from the facts and rules. It
employs a resolution-based mechanism to perform backward chaining, where it works backward
from the goal (query) to the premises (facts and rules) to find a solution. This is done using
unification, a process that matches variables in the query with terms in the knowledge base.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
7. Termination:
It is essential to ensure that Prolog programs terminate for all possible queries. Non-terminating
programs can lead to infinite loops and are generally undesirable.
Prolog's theoretical foundation in logic, along with its mechanism for logical inference, allows it
to express and solve complex problems in a declarative way. Prolog is particularly well-suited for
tasks involving symbolic reasoning, knowledge representation, and search problems. It is widely
used in artificial intelligence, expert systems, natural language processing, and more.
Observation/Program:
Greatest Variable:
max(P,Q,R):-P>Q,P>R,write('Larger number is '),write(P).
max(P,Q,R):-P<Q,Q>R,write('Larger number is '),write(Q).
max(P,Q,R):-R>Q,P<R,write('Larger number is '),write(R).
max(P,Q,R):-P=Q,P<R,write('Larger number is '),write(R).
max(P,Q,R):-P<Q,P=R,write('Larger number is '),write(Q).
max(P,Q,R):-Q=R,P>Q,write('Larger number is '),write(P).
max(P,Q,R):-P=Q,P>R,write('Larger numbers are '),write(P),write(' and '),write(Q).
max(P,Q,R):-P=R,Q<R,write('Larger numbers are '),write(P),write(' and '),write(R).
max(P,Q,R):-Q=R,P<R,write('Larger numbers are '),write(R),write(' and '),write(Q).
max(P,Q,R):-P=Q,P=R,write('All numbers are equal ').
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Factorial:
factorial(0, 1).
factorial(N, Result) :-
N > 0,
Prev is N - 1,
factorial(Prev, PrevFactorial),
Result is N * PrevFactorial.
Palindrome:
reverse_number(N, RevN) :-
reverse_number_helper(N, 0, RevN).
is_palindrome(N) :-
reverse_number(N, RevN),
N =:= RevN.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Prime:
is_prime(2).
is_prime(3).
is_prime(P) :-
integer(P),
P > 3,
P mod 2 =\= 0,
\+ has_factor(P, 3).
has_factor(N, Factor) :-
N mod Factor =:= 0.
has_factor(N, Factor) :-
Factor * Factor < N,
NextFactor is Factor + 2,
has_factor(N, NextFactor).
Conclusion:
In summary, the Prolog implementations for finding the greatest variable, calculating factorial,
checking for palindromes, and determining prime numbers showcase the language's ability to
handle diverse computational tasks effectively. These programs demonstrate Prolog's logical and
declarative nature, making it well-suited for solving a variety of problems with concise and
efficient solutions.
Quiz:
1. In Prolog, what is the purpose of rules, and how are they structured?
In Prolog, rules are used to define relationships between entities or to express logical
implications. They are fundamental constructs that enable Prolog programs to perform
inference and derive conclusions based on the defined logic.
2. Explain the difference between the head and body of a Prolog rule.
Head:
The head of a Prolog rule specifies the relationship or predicate that the rule defines.
It consists of a predicate name followed by zero or more arguments enclosed in
parentheses.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
The head represents the goal or assertion that we're trying to establish or prove.
Body:
The body of a Prolog rule contains the conditions or subgoals that must be satisfied for
the rule's head to be true.
It consists of one or more goals (predicates) separated by commas.
The body represents the conditions under which the head is true.
Suggested Reference:
1. http://lpn.swi-prolog.org/lpnpage.php?pageid=online
2. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
3. “PROLOG Programming For Artificial Intelligence” -By Ivan Bratko( Addison-Wesley)
Problem Completeness
Knowledge Logic
Recognition and accuracy Ethics (2)
Rubrics (2) Building (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Experiment No: 3
Date:
Objectives: To optimize the performance of the A* algorithm by minimizing the number of states
explored and improving the efficiency of the heuristic function.
Theory:
A* Algorithm
A* is a computer algorithm that is widely used in pathfinding and graph traversal, the process of
plotting an efficiently traversable path between multiple points, called nodes. Noted for its
performance and accuracy, it enjoys widespread use.
The key feature of the A* algorithm is that it keeps a track of each visited node which helps in
ignoring the nodes that are already visited, saving a huge amount of time. It also has a list that
holds all the nodes that are left to be explored and it chooses the most optimal node from this list,
thus saving time not exploring unnecessary or less optimal nodes.
So we use two lists namely ‘open list‘ and ‘closed list‘ the open list contains all the nodes that are
being generated and are not existing in the closed list and each node explored after it’s
neighboring nodes are discovered is put in the closed list and the neighbors are put in the open list
this is how the nodes expand. Each node has a pointer to its parent so that at any given point it can
retrace the path to the parent. Initially, the open list holds the start(Initial) node. The next node
chosen from the open list is based on its f score, the node with the least f score is picked up and
explored.
A* uses a combination of heuristic value (h-score: how far the goal node is) as well as the g-score
(i.e. the number of nodes traversed from the start node to current node).
In our 8-Puzzle problem, we can define the h-score as the number of misplaced tiles by
comparing the current state and the goal state or summation of the Manhattan distance between
misplaced nodes.
g-score will remain as the number of nodes traversed from start node to get to the current node.
calculate the h-score by comparing the initial(current) state and goal state and counting the
number of misplaced tiles.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Thus, h-score = 5 and g-score = 0 as the number of nodes traversed from the start node to the
current node is 0.
We first move the empty space in all the possible directions in the start state and calculate the f-
score for each state. This is called expanding the current state.
After expanding the current state, it is pushed into the closed list and the newly generated states
are pushed into the open list. A state with the least f-score is selected and expanded again. This
process continues until the goal state occurs as the current state. Basically, here we are providing
the algorithm a measure to choose its actions. The algorithm chooses the best possible action and
proceeds in that path.
This solves the issue of generating redundant child states, as the algorithm will expand the node
with the least f-score.
It is important to handle edge cases such as unsolvable puzzles, invalid puzzle states, and memory
limitations to avoid program crashes or incorrect results.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Procedure:
1. Define the starting and goal states of the puzzle.
2. Implement the A* algorithm, which uses the heuristic function to determine the best path
to reach the goal state.
Observation/Program:
import heapq
class PuzzleState:
def __init__(self, board, parent=None, move=""):
self.board = board
self.parent = parent
self.move = move
self.g = 0
self.h = 0
def __hash__(self):
return hash(str(self.board))
def is_goal(self):
return self.board == [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
def get_blank_position(self):
for i in range(3):
for j in range(3):
if self.board[i][j] == 0:
return i, j
def manhattan_distance(state):
distance = 0
for i in range(3):
for j in range(3):
if state.board[i][j] != 0:
target_i, target_j = divmod(state.board[i][j], 3)
distance += abs(i - target_i) + abs(j - target_j)
return distance
def solve_puzzle(initial_state):
open_list = []
closed_set = set()
heapq.heappush(open_list, initial_state)
while open_list:
current_state = heapq.heappop(open_list)
if current_state.is_goal():
path = []
while current_state.parent:
path.append(current_state.move)
current_state = current_state.parent
return path[::-1]
closed_set.add(current_state)
return None
if __name__ == "__main__":
initial_board = [[1, 2, 3], [4, 0, 5], [6, 7, 8]]
initial_state = PuzzleState(initial_board)
solution = solve_puzzle(initial_state)
if solution:
print("Solution steps:", solution)
else:
print("No solution found."
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Conclusion:
In conclusion, the implementation of the A* algorithm for solving the 8 Puzzle Problem
showcases the algorithm's effectiveness in finding optimal solutions efficiently. This program
highlights the power of heuristic search techniques in navigating complex problem spaces and
finding the most promising paths towards the goal state. By leveraging the A* algorithm, the
solution demonstrates an intelligent approach to solving puzzles, providing insights into how
algorithms can be applied to real-world problem-solving scenarios.
Quiz:
1. How do you generate successor states in the A* algorithm for solving the 8 Puzzle
Problem, and what information do you need to calculate their f-scores?
In the A* algorithm for solving the 8 Puzzle Problem, generating successor states involves
moving the blank tile (represented by the number 0) in the puzzle board to adjacent
positions (up, down, left, or right) to create new board configurations. These new
configurations represent possible moves from the current state to potential successor
states.
2. How does the A* algorithm decide which state to explore next in the search space,
and why is this decision important for the efficiency of the algorithm?
The A* algorithm decides which state to explore next in the search space based on a
combination of two factors: the cost to reach the current state from the initial state (g-
score) and the estimated cost from the current state to the goal state (h-score). These
factors are combined into the f-score, which is used to prioritize which states to explore
next.
Suggested References:
1. http://lpn.swi-prolog.org/lpnpage.php?pageid=online
2. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
3. “PROLOG Programming For Artificial Intelligence” -By Ivan Bratko( Addison-Wesley)
Problem Completeness
Knowledge Logic
Recognition and accuracy Ethics (2)
Rubrics (2) Building (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Experiment No: 4
Date:
Objectives: Learning about lists in Prolog is a fundamental and valuable concept as it allows you
to work with structured data and perform a wide range of tasks.
Theory:
Lists are a fundamental data structure in Prolog, allowing you to work with collections
of elements. In Prolog, a list is a sequence of terms enclosed in square brackets (`[ ]`).
Lists can contain a mix of elements, including atoms, variables, and other lists. Here's
an overview of the theory behind lists in Prolog:
1. List Syntax:
- In Prolog, lists are denoted by square brackets, such as `[a, b, c]`, which represents a
list of three atoms: 'a,' 'b,' and 'c.'
- Lists can be empty, represented as `[]`.
2. List Elements:
- Lists in Prolog can contain a mix of elements, including:
- Atoms (e.g., `a`, `b`, `c`)
- Variables (e.g., `X`, `Y`)
- Other lists (e.g., `[a, [b, c], d]`)
Artificial Intelligence (3170716) Enrollment Number: 21060116087
3. List Construction:
- Lists can be constructed using the "cons" operator, represented as `|` (often referred
to as "pipe").
- The "cons" operator allows you to prepend an element to an existing list or split a
list into its head and tail.
- For example, `[X | Rest]` represents a list with the first element `X` and the
remaining elements in `Rest`.
4. List Operations:
- Prolog provides various built-in predicates for working with lists, including:
- `length/2`: Finding the length of a list.
- `append/3`: Concatenating lists.
- `member/2`: Checking if an element is a member of a list.
- `nth0/3` and `nth1/3`: Accessing elements at a specific position in the list.
- `reverse/2`: Reversing a list.
- `select/3`: Removing an element from a list.
- `permutation/2`: Generating permutations of a list.
6. List Comprehensions:
- Prolog supports list comprehensions, which provide a declarative way to generate
lists based on conditions.
- List comprehensions are concise and resemble set-builder notation.
7. Higher-Order Predicates:
- Prolog allows you to define and use higher-order predicates that take lists as
arguments.
- Higher-order predicates can simplify list processing, making code more elegant and
concise.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Understanding lists in Prolog is crucial for a wide range of applications, from basic data
manipulation to complex problem-solving. Lists are a versatile data structure that
enables you to represent and process structured information efficiently in Prolog.
Observation/Program:
a.
FirstElement([First|_], First).
b.
last_element([Last],Last).
last_element([_|Rest],Last) :- last_element(Rest,Last).
c.
display_all([]).
disaplay_all([X|Rest]) :- write(x) ,write(‘’),display_all(Rest).
d.
elements_up_to(_,[ ],[ ]).
elements_up_to(0, _,[ ]).
elements_up_to(N.[X|Xs],[X|Ys]) :-
N> 0,
NextN is N-1,
elements_up_to(nextN,Xs,Ys).
e.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
count_elements( [ ], 0).
count_elements( [_|Rest],Count ) :-
count_elements( Rest, RestCount),
Count is RestCount + 1.
f.
count_odd_even ([], 0, 0).
count_odd_even([X|Xs], OddCount, EvenCount) :-
0 is X mod 2,
count_odd_even(Xs, OddCount, RestEvenCount),
EvenCount is RestEvenCount + 1.
count_odd_even([X|Xs], OddCount, EvenCount) :-
1 is X mod 2,
count_odd_even(Xs, RestOddCount, EvenCount),
OddCount is RestOddCount + 1.
Output:
a.
b.
c.
d.
e.
f.
Conclusion:
In conclusion, the implementation of the Prolog programs based on lists demonstrates the
language's capability to manipulate and analyze list data efficiently. These programs showcase
Prolog's versatility in handling various list operations, from accessing specific elements to
counting occurrences of certain elements. By implementing functionalities such as displaying the
first and last elements, showing all elements, extracting elements up to a specified index, and
counting the number of elements, Prolog proves to be a powerful tool for list manipulation tasks.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Additionally, the program to count odd and even elements showcases Prolog's ability to perform
computations and categorize elements based on specific criteria. Overall, these implementations
highlight Prolog's suitability for list processing tasks and its potential in solving a wide range of
computational problems.
Quiz:
1. Pattern Matching: You can directly match the list with its first element and the rest of the list
using the cons operator `|`.
For example: first_element([FirstElement | _], FirstElement).
This predicate `first_element/2` succeeds if its first argument is a list and its second argument
unifies with the first element of that list.
2. Using `nth0/3: The `nth0/3` predicate allows you to access the element at a specific index in a
list. You can use it to access the first element by specifying an index of `0`.
For example: nth0(0, List, FirstElement).
This predicate succeeds if `List` is a list and `FirstElement` unifies with its first element.
2. Generating Lists of a Specified Length: If you provide a variable as the first argument and an
integer as the second argument, Prolog will generate lists of the specified length.
For example:
?- length(List, 3).
List = [_6784, _6790, _6796].
This generates a list `List` with three unbound variables.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. “PROLOG Programming For Artificial Intelligence” -By Ivan Bratko( Addison-Wesley)
Marks
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Experiment No: 5
Date:
Objectives: The water jug problem, also known as the "water pouring problem" or "die hard
problem," is a classic puzzle in which the objective is to find a sequence of actions to measure a
specific volume of water using two jugs of known capacities. The problem involves critical
thinking and can be used to practice problem-solving skills.
Theory:
The water jug problem, also known as the "water pouring problem" or "die hard problem," is a
classic puzzle that involves finding a sequence of actions to measure or obtain a specific
volume of water using two jugs of known capacities. The problem can vary in complexity
depending on the specific constraints provided. Here is the theoretical background and the key
elements of the water jug problem:
Problem Statement:
- The problem typically involves two jugs with known capacities, often referred to as Jug A
and Jug B.
- There is usually a target volume of water that you need to measure or achieve using the jugs.
1. Jug Capacities: Each jug has a known capacity, which is the maximum amount of water it
can hold. The capacities of Jug A and Jug B are usually given.
2. Initial State: The problem starts with the jugs in a certain initial state, which includes the
amounts of water in each jug (possibly zero).
3. Goal State: The objective is to reach a goal state where a specific volume of water (the
target) is present in one of the jugs.
1. Pouring: You can pour water from one jug to another or pour water into or out of the jugs.
Pouring water is typically allowed in discrete amounts and follows certain rules:
- You can pour water from one jug into another until the receiving jug is full or the pouring
jug is empty.
2. Wastage: Some variations of the problem may allow for, or restrict, wastage of water
during the pouring process. Wastage occurs when water is poured out and not used in the
target measurement.
The primary objective of the water jug problem is to find a sequence of pouring actions that
will result in the desired volume of water being present in one of the jugs. The problem can be
solved through various approaches:
2. Mathematical Analysis: In some cases, the problem can be solved through mathematical
modeling and equations. The mathematical approach may aim to find the optimal sequence of
actions.
Variations:
The water jug problem has multiple variations, including different jug capacities, additional
constraints (e.g., limited pouring steps), and variations that involve more than two jugs. Each
variation presents a unique challenge and may require a different approach.
Applications:
While the water jug problem is a classic puzzle, it also has practical applications, such as
modeling fluid transfers, understanding capacity constraints in logistics, and demonstrating
problem-solving techniques in artificial intelligence and computer science.
Solving the water jug problem serves as an excellent exercise in critical thinking, problem-
solving, and algorithm design, making it a valuable educational tool and a fascinating logic
puzzle.
Procedure:
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Observation/Program:
initial((0, 0)).
final((2, _)).
final((_, 1)).
move((X, Y), (4, Y)) :- X < 4.
move((X, Y), (X, 3)) :- Y < 3.
move((X, Y), (0, Y)) :- X > 0.
move((X, Y), (X, 0)) :- Y > 0.
move((X, Y), (NewX, NewY)) :-
X > 0,
Y < 3,
Diff is min(X, 3 - Y),
NewX is X - Diff,
NewY is Y + Diff.
move((X, Y), (NewX, NewY)) :-
Y > 0,
X < 4,
Diff is min(Y, 4 - X),
NewX is X + Diff,
NewY is Y - Diff.
solve(State, _) :-
final(State),
write('Solution found: '), write(State), nl.
solve(State, Visited) :-
move(State, NextState),
\+ member(NextState, Visited),
solve(NextState, [NextState|Visited]).
Output:
Conclusion:
In summary, the Prolog program for solving the water jug problem efficiently finds a solution by
leveraging the language's logical and recursive capabilities. By representing the problem's
constraints and rules as logical statements, the program navigates through possible states to reach
the desired outcome. This implementation demonstrates Prolog's suitability for solving
combinatorial problems through its declarative nature, making it easier to express and solve
complex puzzles like the water jug problem. Overall, the solution showcases Prolog's
effectiveness in handling logical puzzles and highlights its potential for solving a wide range of
algorithmic challenges.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Quiz:
2. What are the two fundamental actions that you can perform with the jugs in the
problem?
Filling a jug: You can fill one of the jugs with water from a water source until it is full.
Emptying a jug: You can empty the contents of one of the jugs onto the ground,
effectively making it empty.
3. If Jug A has a capacity of 5 liters and Jug B has a capacity of 3 liters, what is the
minimum number of steps required to measure exactly 4 liters of water?
To measure exactly 4 liters of water using a 5-liter jug (jug A) and a 3-liter jug (jug B),
you can follow these steps:
1. Fill jug A (5 liters).
2. Pour water from jug A into jug B until jug B is full (3 liters).
3. At this point, jug A has 2 liters of water remaining (5 - 3).
4. Empty jug B.
5. Pour the 2 liters of water from jug A into jug B.
6. Fill jug A again (5 liters).
7. Pour water from jug A into jug B until jug B is full. Since jug B can only hold 1
more liter, only 1 liter will be poured from jug A.
8. At this point, jug A has 4 liters of water remaining (5 - 1).
Thus, the minimum number of steps required to measure exactly 4 liters of water is
Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. “PROLOG Programming For Artificial Intelligence” -By Ivan Bratko( Addison-Wesley)
Marks
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Experiment No: 6
Implement the Minimax algorithm for a simple tic-tac-toe game using Python Language.
Date:
Objectives: To illustrate how to recursively apply the Minimax algorithm to build a game tree
and determine the optimal move for the computer player.
Theory:
The Minimax Algorithm is a popular decision-making algorithm used in game
theory, which allows a player to determine the best possible move to make, given
that the opponent will also make the best possible move.
Here's a general implementation of the Minimax algorithm:
Define the game state: The game state should be defined in terms of the current
state of the board or game, including the position of all pieces, scores, and any
other relevant information.
Define the game tree: The game tree represents all the possible moves that can be
made from the current game state, and the resulting game states that will arise
from each move. The game tree can be constructed recursively, with the root node
representing the current game state, and the child nodes representing the possible
moves that can be made from that state.
Assign scores to each game state: At the bottom of the game tree, assign a score
to each game state based on the outcome of the game from that state. For
example, if the game is won by the player who reached that state, assign a
positive score, and if the game is lost, assign a negative score.
Determine the best move: Starting from the root node, alternate between selecting
the move that maximizes the score for the player and selecting the move that
minimizes the score for the opponent until you reach a leaf node. The score of that
leaf node will then be propagated back up the tree to the root node, and the best
move will be the one that leads to the highest score.
Handle edge cases such as invalid moves, repeated moves, and game-ending conditions to avoid
program crashes or incorrect results.
Procedure:
1. Define an evaluation function to evaluate the game state and return a score.
2. Define a recursive function to search for the best move using the Minimax
Artificial Intelligence (3170716) Enrollment Number: 21060116087
algorithm.
3. Create a function to get the best move for the current player.
Observation/Program:
import sys
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_winner(board):
# Check rows
for row in board:
if row.count(row[0]) == len(row) and row[0] != " ":
return row[0]
# Check columns
for col in range(len(board)):
if board[0][col] == board[1][col] == board[2][col] and board[0][col] != " ":
return board[0][col]
# Check diagonals
if board[0][0] == board[1][1] == board[2][2] and board[0][0] != " ":
return board[0][0]
if board[0][2] == board[1][1] == board[2][0] and board[0][2] != " ":
return board[0][2]
return None
def get_empty_cells(board):
empty_cells = []
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == " ":
empty_cells.append((i, j))
return empty_cells
if winner:
if winner == "X":
return 1
elif winner == "O":
return -1
else:
return 0
if is_maximizing:
best_score = -sys.maxsize
for i, j in get_empty_cells(board):
board[i][j] = "X"
score = minimax(board, depth + 1, False)
board[i][j] = " "
best_score = max(score, best_score)
return best_score
else:
best_score = sys.maxsize
for i, j in get_empty_cells(board):
board[i][j] = "O"
score = minimax(board, depth + 1, True)
board[i][j] = " "
best_score = min(score, best_score)
return best_score
def find_best_move(board):
best_score = -sys.maxsize
best_move = None
for i, j in get_empty_cells(board):
board[i][j] = "X"
score = minimax(board, 0, False)
board[i][j] = " "
if score > best_score:
best_score = score
best_move = (i, j)
return best_move
def main():
board = [[" " for _ in range(3)] for _ in range(3)]
print("Welcome to Tic Tac Toe!")
print_board(board)
while True:
player_move = input("Enter your move (row column): ").split()
row, col = map(int, player_move)
if board[row][col] == " ":
Artificial Intelligence (3170716) Enrollment Number: 21060116087
board[row][col] = "O"
print_board(board)
winner = check_winner(board)
if winner:
if winner == "draw":
print("It's a draw!")
else:
print(f"{winner} wins!")
break
print("Computer's move:")
comp_row, comp_col = find_best_move(board)
board[comp_row][comp_col] = "X"
print_board(board)
winner = check_winner(board)
if winner:
if winner == "draw":
print("It's a draw!")
else:
print(f"{winner} wins!")
break
else:
print("Invalid move. Try again.")
if __name__ == "__main__":
main()
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Conclusion:
In summary, the implementation of the Minimax algorithm for a simple tic-tac-toe game in
Python demonstrates the algorithm's capability to determine optimal moves in adversarial
situations. This program showcases the power of decision-making algorithms in strategic games,
providing insights into how AI techniques can be applied to solve real-world problems. By
leveraging Minimax, the solution efficiently navigates the game tree to find the best possible
moves, enhancing the gameplay experience and offering a glimpse into the potential of AI-driven
decision-making processes.
Quiz:
1. How can you optimize the Minimax algorithm to improve its performance in Tic
Tac Toe?
There are several ways to optimize the Minimax algorithm to improve its performance in
Tic Tac Toe:
Alpha-Beta Pruning
Transposition Tables
Move Ordering
Heuristic Evaluation Function
Iterative Deepening
2. Can the Minimax algorithm be used for games other than Tic Tac Toe? If so, what
are some examples?
Yes, the Minimax algorithm can be used for a wide variety of two-player zero-sum
games, not just Tic Tac Toe. Any game where players take turns making moves and the
outcome is determined solely by the actions of the players (i.e., there is no random
chance involved) can potentially be solved using Minimax.
Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Machine Learning with Python for Everyone, Mark Fenner, Pearson
3. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
4. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley
Problem Completeness
Knowledge Logic
Recognition and accuracy Ethics (2)
Rubrics (2) (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Experiment No: 7
Implement Bayesian Networks algorithm for the Monty Hall Problem using any
programming Language.
Date:
Objectives:To understand how Bayesian Networks can be used to represent and reason about
uncertain knowledge.
Theory:
Bayesian Networks is a probabilistic graphical model used for representing and reasoning about
uncertain knowledge. It consists of a directed acyclic graph (DAG) where nodes represent random
variables and edges represent dependencies between them. Each node has a conditional
probability distribution (CPD) that describes the probability of that node given its parents.
Bayesian Networks can be used for a wide range of tasks including prediction, classification,
diagnosis, and decision-making.
The algorithm for constructing a Bayesian Network involves the following steps:
Identify the random variables: The first step is to identify the random variables that are
relevant to the problem. These variables can be discrete or continuous, and can represent
events, states, or properties.
Define the dependencies: The next step is to define the dependencies between the
variables. This is done by specifying the causal relationships between the variables, and
determining which variables are parents and which are children.
Assign probabilities: The next step is to assign probabilities to the variables. This involves
specifying the prior probabilities for each variable, as well as the conditional probabilities
for each node given its parents.
Construct the graph: The final step is to construct the DAG by connecting the nodes
according to their dependencies, and specifying the CPDs for each node.
It is a famous probability puzzle based on a game show scenario. The problem is named after
Monty Hall, the host of the game show "Let's Make a Deal".
The scenario goes as follows:
There are three doors, behind one of which is a prize, and behind the other two are goats.
The player chooses one door, and then the host, who knows what is behind each door,
opens one of the other two doors to reveal a goat. The player is then given the option to
switch their choice to the other unopened door or stick with their original choice.
The question is: should the player switch their choice, or stick with their original choice?
The answer is that the player should always switch their choice.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Ensure that the algorithm produces accurate results, it is important to validate the input
data to ensure that it is consistent and complete.
Procedure:
1. Define an evaluation function to evaluate the game state and return a score.
2. Define a recursive function to search for the best move using the Minimax
algorithm.
3. Create a function to get the best move for the current player.
Observation/Program:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
Output:
Conclusion:
Switching doors after Monty opens one increases the player's chances of winning the car, as
confirmed by the Bayesian Network algorithm used in the code. This conclusion aligns with the
optimal strategy in the Monty Hall Problem and showcases the effectiveness of probabilistic
Quiz:
1. What is inference in a Bayesian Network?
Inference in a Bayesian Network is the process of using the network's structure and
probabilistic reasoning to calculate probabilities or make predictions about unobserved
variables given observed evidence. It involves updating probabilities based on Bayes'
theorem and the dependencies between variables in the network. Inference allows us to
estimate the likelihood of various outcomes and make informed decisions based on
available information.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Machine Learning with Python for Everyone, Mark Fenner, Pearson
3. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
4. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley
References used by the students:
Marks
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Experiment No: 8
Date:
Familiarity with neural networks, which are computational models inspired by the structure and
function of the brain.
Familiarity with a neural network tool.
Objectives:Learn a tool should be selected that provides an easy-to-use interface for designing,
training, and deploying Connectionist Model.
Theory:
Connectionist Models
Neural networks are by far the most commonly used connectionist model today.
Though there are a large variety of neural network models, they almost always follow two
basic principles regarding the mind:
Any mental state can be described as an (N)-dimensional vector of numeric activation
values over neural units in a network.
Memory is created by modifying the strength of the connections between neural units. The
connection strengths, or "weights", are generally represented as an N×N matrix.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Observation/Program:
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Conclusion:
Artificial Intelligence (3170716) Enrollment Number: 21060116087
The conclusion of the troubleshooting steps for import errors related to TensorFlow is that
resolving such issues often requires a systematic approach that involves checking the Python
environment, verifying the installation of TensorFlow, ensuring correct configuration in the IDE,
checking for typos, and considering system path settings. By following these steps, users can
identify and resolve common issues that may arise when importing TensorFlow in Python scripts
or projects. If problems persist after taking these steps, further investigation may be necessary,
such as checking system dependencies, consulting documentation, or seeking assistance from
online communities or support channels
Quiz:
Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Neural Networks, Fuzzy Logic, and Genetic Algorithms: Synthesis and Applications By
S. Rajshekharan, G. A. Vijayalakshmi Pai, PHI
3. Machine Learning with Python for Everyone, Mark Fenner, Pearson
4. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
5. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley
Problem Logic
Knowledge Tool Usage
Recognition Building Ethics (2)
Rubrics (2) (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Experiment No: 9
Date:
Understanding of genetic algorithms, which are a class of optimization algorithms that are
inspired by the principles of natural selection and genetics.
Knowledge of a programming language
Objectives:To use a computational approach that mimics the process of natural selection to solve
optimization problems
Equipment/InstrumentsProgramming language
Theory:
Genetic Algorithm (GA) is a popular meta heuristic optimization algorithm in the field of artificial
intelligence (AI).Genetic Algorithms are based on the theory of natural selection and work on
generating a set of random solutions and making them compete in an arena where only the fittest
survive. It is often used to solve complex optimization problems where other traditional methods
may not work well.
The first step in using GA for an AI problem is to define the problem as an optimization problem.
This involves identifying the objective function that needs to be optimized and the constraints (if
any) that need to be satisfied.
Once the problem is defined, the next step is to create an initial population of candidate solutions.
The population is typically generated randomly or using some heuristics depending on the
problem.
The fitness function is then defined, which evaluates each chromosome in the population based on
how well it satisfies the objective function and constraints.
Next, the GA applies selection, crossover, and mutation operators to create new and hopefully
better solutions. Selection involves choosing the top-performing chromosomes to be carried over
to the next generation. Crossover involves combining two chromosomes to create new offspring.
Mutation involves randomly changing some genes in a chromosome to introduce diversity into the
population.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
The GA then repeats the process of selection, crossover, and mutation for a number of generations
or until a stopping criterion is met (such as reaching a maximum number of generations or finding
an optimal solution).
It is important to define clear objectives and constraints for the optimization problem.
It is crucial to validate the fitness function.
Procedure:
1. Define the problem
2. Define the representation
3. Initialize the population.
4. Evaluate the fitness
5. Select parents.
6. Create offspring: Use genetic operators such as crossover and mutation to create offspring
from the selected parents.
7. Evaluate the offspring.
8. Select survivor
9. Check stopping criteria
Observation/Program:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
class Individual {
private List<Integer> genes;
private int fitness;
child2.setGenes(child2Genes);
return new Individual[]{child1, child2};
}
Output:
Conclusion:
The Genetic Algorithm effectively evolves solutions towards the target "Hello, Genetic
Algorithm!" by iteratively selecting, combining, and mutating solutions in a population. It
demonstrates its ability to search and optimize solutions in a search space efficiently.
Quiz:
1. What are the genetic operators that will be used to create new individuals in each
generation? Will you use crossover, mutation, or both?
In the Genetic Algorithm provided, both crossover and mutation are used as genetic
operators to create new individuals in each generation.
Crossover: This operator combines genetic information from two parent individuals to
create one or more new child individuals. In the code, the crossover function performs a
single-point crossover by randomly selecting a crossover point and swapping genetic
information between two parents to create a child.
Mutation: This operator introduces genetic diversity by randomly changing a small part
of an individual's genetic information. In the code, the mutate function randomly changes
one character in a solution to create a mutated version of the individual.
2. How will you evaluate the fitness of each individual in the population? Will you
Artificial Intelligence (3170716) Enrollment Number: 21060116087
3. What is the stopping criterion for the genetic algorithm? Will you stop when a
certain fitness level is reached, after a certain number of generations, or when the
algorithm converges?
The Genetic Algorithm stops when it finds a solution whose fitness score matches the
length of the target solution. This stopping criterion indicates that the algorithm has
converged to an optimal or near-optimal solution. By reaching this fitness level, the
algorithm achieves its goal of finding a solution that meets the specified criteria, and
further iterations are not necessary. This stopping criterion ensures that the algorithm
terminates efficiently once the desired level of fitness or solution quality is attained.
Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Neural Networks, Fuzzy Logic, and Genetic Algorithms: Synthesis and Applications By
S. Rajshekharan, G. A. Vijayalakshmi Pai, PHI
3. Machine Learning with Python for Everyone, Mark Fenner, Pearson
4. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
5. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley
Problem Logic
Knowledge Tool Usage
Recognition Building Ethics (2)
Rubrics (2) (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Experiment No: 10
Date:
Objectives: The Tower of Hanoi problem is a classic mathematical puzzle that involves moving
a stack of disks from one peg to another while adhering to specific rules. The primary objective is
to find a sequence of moves that allows you to transfer the entire stack to a different peg.
Theory:
The Tower of Hanoi is a classic mathematical puzzle that was invented by the French
mathematician Édouard Lucas in 1883. It consists of three pegs and a number of disks of different
sizes, which can be slid onto any peg. The puzzle's objective is to move the entire stack of disks
from one peg to another, subject to the following rules:
2. Initial Configuration: The puzzle begins with all the disks stacked in decreasing order of size
on one peg, typically peg A. The smallest disk is on top, and the largest disk is at the bottom.
3. Goal Configuration: The goal is to move the entire stack of disks to another peg, typically peg
C. The disks should be stacked in the same order (smallest on top, largest on the bottom) on the
destination peg.
4. Intermediate Peg: You can use peg B as an intermediate peg to move the disks. This means
that you can only move one disk at a time from the top of one peg to the top of another peg.
5. Larger Disk on Top: A disk can never be placed on top of a smaller disk.
1. Recursion: The Tower of Hanoi problem is inherently recursive in nature. To solve a problem
with n disks, you can break it down into smaller subproblems, such as moving the top n-1 disks to
an intermediate peg, moving the largest disk to the destination peg, and then moving the n-1 disks
from the intermediate peg to the destination peg. This recursive decomposition is a fundamental
aspect of the problem.
Artificial Intelligence (3170716) Enrollment Number: 21060116087
2. Minimum Number of Moves: The minimum number of moves required to solve the Tower of
Hanoi problem with n disks is 2^n - 1. This is a well-established theoretical result and is used as a
basis for understanding the problem's complexity.
3. Recursive Formula: The number of moves required to solve the Tower of Hanoi problem for n
disks can be described by the recursive formula: `H(n) = 2 * H(n-1) + 1`, with the base case `H(1)
= 1`.
4. Mathematical Induction: Mathematical induction can be used to prove the minimum number
of moves required to solve the Tower of Hanoi problem for any number of disks.
5. Generalizations: The Tower of Hanoi problem can be generalized to include more than three
pegs, leading to variations like the Tower of Hanoi with four or more pegs. These generalizations
introduce new challenges and require different strategies for solving the problem.
6. Educational Significance: The Tower of Hanoi is often used as an educational tool to teach
concepts of recursion, mathematical induction, and algorithm design. It serves as a classic
example of a problem that can be solved using recursive algorithms.
The Tower of Hanoi problem, with its elegant mathematical properties and recursive nature,
continues to be a fundamental puzzle in computer science, mathematics, and education. It
exemplifies the power of recursion in problem-solving and serves as a valuable teaching and
learning tool.
The program should handle exceptions, such as input errors or invalid operations.
Procedure:
Observation/Program:
Output:
Artificial Intelligence (3170716) Enrollment Number: 21060116087
Conclusion:
In conclusion, the Tower of Hanoi problem has been successfully solved using Prolog,
demonstrating the language's capability to elegantly express recursive algorithms. The program
efficiently moves the disks from one peg to another while adhering to the rules of the puzzle. By
leveraging Prolog's logic-based paradigm, the solution elegantly represents the recursive nature of
the Tower of Hanoi problem, making it easy to understand and implement. This implementation
underscores Prolog's suitability for expressing and solving complex, recursive problems,
showcasing its versatility in algorithmic problem-solving.
Quiz:
1. What is the role of an intermediate peg (e.g., peg B) in the Tower of Hanoi problem,
and how does it help solve the problem?
In the Tower of Hanoi problem, the role of an intermediate peg (e.g., peg B) is crucial for
solving the problem efficiently. The intermediate peg serves as a temporary holding place
for moving disks during the process of transferring the tower from the source peg to the
destination peg.
The key insight behind the Tower of Hanoi problem is the recursive nature of the solution.
By using an intermediate peg, we can break down the problem of moving a tower of \( n \)
disks from the source peg to the destination peg into smaller subproblems:
1. Move the top \( n-1 \) disks from the source peg to the intermediate peg.
2. Move the largest disk (the \( n \)th disk) from the source peg to the destination peg.
3. Move the \( n-1 \) disks from the intermediate peg to the destination peg.
By recursively applying these steps, we can solve the Tower of Hanoi problem for any
number of disks. The intermediate peg allows us to keep the disks organized and ensures
that we never place a larger disk on top of a smaller one, which is a key constraint of the
problem. This approach enables an elegant and efficient solution to the Tower of Hanoi
problem.
2. Is it possible to solve the Tower of Hanoi problem with more than three pegs? If so,
how many pegs can be used, and what variations are introduced?
Yes, it is possible to solve the Tower of Hanoi problem with more than three pegs. The
generalization of the Tower of Hanoi problem to more than three pegs is known as the
"Tower of Hanoi with more pegs" problem or the "Tower of Hanoi with \( k \) pegs"
problem.
In the traditional Tower of Hanoi problem, we have three pegs (often labeled A, B, and C),
but in the generalized version, we can have any number of pegs. Let's denote the number
of pegs as \( k \), where \( k > 3 \).
Artificial Intelligence (3170716) Enrollment Number: 21060116087
With more than three pegs, the goal is still to move a tower of \( n \) disks from one peg
(the source peg) to another peg (the destination peg), using the remaining pegs as
intermediates, without ever placing a larger disk on top of a smaller one.
The minimum number of pegs required to solve the Tower of Hanoi problem with \( n \)
disks is \( n+2 \). Therefore, to solve the Tower of Hanoi problem with \( n \) disks using \(
k \) pegs, where \( k \geq n+2 \), is possible.
The Tower of Hanoi problem with more than three pegs introduces variations in the
recursive algorithm used for solving it. The traditional recursive algorithm for three pegs is
not directly applicable.
3. What is the educational significance of the Tower of Hanoi problem, and how is it
commonly used in teaching and learning?
The Tower of Hanoi problem holds significant educational value and is commonly used in
teaching and learning in various fields due to its rich mathematical and computational
properties. Some of its educational significance includes:
Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. https://www.geeksforgeeks.org/artificial-intelligence-an-introduction/
Rubric wise marks obtained:
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks