Artificial Intelligence (3161608) : B.E. Semester 6 (Information Technology)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 62

Artificial Intelligence (3170716) Enrollment Number: 21060116087

A Laboratory Manual for

Artificial Intelligence
(3161608)

B.E. Semester 6
(Information Technology)

Directorate of Technical Education, Gandhinagar,


Gujarat
Artificial Intelligence (3170716) Enrollment Number: 21060116087

Government Engineering College, Modasa


Department of Information Technology

Certificate

This is to certify that Mr. /Ms. ___________________________________


________ Enrollment No. _______________of B.E. Semester _____
Information Technology of this Institute (GTU Code: _____ ) has
satisfactorily completed the Practical / Tutorial work for the subject Artificial
Intelligence (3161608)for the academic year ____________.

Place: __________
Date: __________

Name and Sign of Faculty member

Head of the Department


Artificial Intelligence (3170716) Enrollment Number: 21060116087

DTE’s Vision

 To provide globally competitive technical education


 Remove geographical imbalances and inconsistencies
 Develop student friendly resources with a special focus on girls’ education and support to
weaker sections
 Develop programs relevant to industry and create a vibrant pool of technical professionals

Institute’s Vision

 To be a leading institution ensuring Academic Excellence, Research, Nurturing Innovation


and Entrepreneurial Attitude to produce competent technocrats for service to Nation.

Institute’s Mission

 To be a student centric institute imbibing experiential, innovative and lifelong learning


skills, addressing societal problems.
 To create a conducive ecosystem for Research, innovation & extension services.
 To inculcate entrepreneurial attitude and values amongst Learners.
 To Collaborate with Industries and other institutions to strengthen symbiotic relations.
 To mentor aspiring Institutions to unleash their potential, towards nation building.
Department’s Vision

 To create an environment for providing value-based education in Information Technology


through innovation, team work and ethical practices.

Department’s Mission

 To produce Information Technology graduates according to the needs of industry,


government, society and scientific community.
 To develop state of the art computing facilities and academic infrastructure.
 To develop partnership with industries, government agencies and R & D organizations for
knowledge sharing and overall development of faculties and students.
 To solve industrial, governance and societal issues by applying computing techniques.
 To create environment for research and entrepreneurship.
Artificial Intelligence (3170716) Enrollment Number: 21060116087

Programme Outcomes (POs)

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and
environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
Artificial Intelligence (3170716) Enrollment Number: 21060116087

Program Specific Outcomes (PSOs)

 Sound knowledge of fundamentals of computer science and engineering including


software and hardware.
 Develop the software using sound software engineering principles having web
based/mobile based interface.
 Use various tools and technology supporting modern software frameworks for solving
problems having large volume of data in the domain of data science and machine learning.

Program Educational Objectives (PEOs)

 Possess technical competence in solving real life problems related to Computing.


 Acquire good analysis, design, development, implementation and testing skills to
formulate simple computing solutions to the business and societal needs.
 Provide requisite skills to pursue entrepreneurship, higher studies, research, and
development and imbibe high degree of professionalism in the fields of computing.
 Embrace life-long learning and remain continuously employable.
 Work and excel in a highly competence supportive, multicultural and professional
environment which abiding to the legal and ethical responsibilities.
Artificial Intelligence (3170716) Enrollment Number: 21060116087

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

Practical – Course Outcome matrix

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. √

Implement following prolog programs based


on list.
a. To display first element of a list.
b. To display last element of a list.
4. c. To display all element of a list √ √
d. To display elements up to specified index of
a list.
e. To count number of elements in a list.
f. To count odd and even elements of a list
Write a prolog program to solve water jug problem.
5. √ √
Implement the Minimax algorithm for a simple tic-
6. √
tac-toe game using Python Language.
Artificial Intelligence (3170716) Enrollment Number: 21060116087

Implement Bayesian Networks algorithm for the


7. Monty Hall Problem using any programming √
Language.
8. Demonstrate Connectionist Model using Tool. √ √
Implement Genetic Algorithm using any
9. √
programming Language.
Write a prolog program to solve Tower of Hanoi
10. √ √
problem.
Artificial Intelligence (3170716) Enrollment Number: 21060116087

Guidelines for Faculty members

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.

Instructions for Students

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.

Common Safety Instructions

Students are expected to


1. switch on the PC carefully (not to use wet hands)
2. shutdown the PC properly at the end of your Lab
3. carefully handle the peripherals (Mouse, Keyboard, Network cable etc).
4. use Laptop in lab after getting permission from Teacher
Artificial Intelligence (3170716) Enrollment Number: 21060116087

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.

Implement following prolog programs


based on list.
a. To display first element of a list.
b. To display last element of a list.
c. To display all element of a list
4.
d. To display elements up to specified
index of a list.
e. To count number of elements in a list.
f. To count odd and even elements of a
list
Artificial Intelligence (3170716) Enrollment Number: 21060116087

Write a prolog program to solve water jug


5.
problem.
Implement the Minimax algorithm for a simple
6.
tic-tac-toe game using Python Language.
Implement Bayesian Networks algorithm for
7. the Monty Hall Problem using any
programming Language.
Demonstrate Connectionist Model using
8.
Tool.
Implement Genetic Algorithm using
9.
any programming Language.
Write a prolog program to solve Tower of
10.
Hanoi problem.
Total
Artificial Intelligence (3170716) Enrollment Number: 21060116087

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

Relevant CO: CO1

Objectives: To learn different kinds of knowledge bases of Prolog Programming.


To create a powerful and flexible system for representing, manipulating, and
reasoning about information in a logical and structured way.

Equipment/Instruments: Personal Computer, SWI-Prolog Interpreter

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

We can ask Prolog whether Mia is a woman by posing the query:

?- 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

KB3, our third knowledge base, consists of five clauses:


happy(vincent).
listens2Music (butch). playsAirGuitar (vincent):-
listens 2Music(vincent),
happy(vincent). playsAirGuitar(butch):-
happy(butch).
playsAirGuitar(butch):-
listens2Music(butch). There are two facts, happy(vincent) and listens2Music(butch), and three
rules.
KB3 defines the same three predicates as KB2 (namely happy, listens2Music, and playsAirGuitar)
but it defines them differently. In particular, the three rules that define the playsAirGuitar
predicate introduce some new ideas.

Knowledge Base 4

Here is KB4, our fourth knowledge base:


woman(mia).
woman(jody).
woman (yolanda).
loves (vincent,mia).
loves (marsellus,mia).
loves (pumpkin, honey_bunny).
loves (honey_bunny, pumpkin).
Artificial Intelligence (3170716) Enrollment Number: 21060116087

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.

Safety and necessary Precautions:

Use appropriate names and arguments for the predicates.


Make sure that the rules are accurate and cover all possible cases.

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

write('Enter Password: '), read(Password),


login(Username, Password),
write('Login Successful').
start:-
write('Login Unsuccessful'), nl,
write('Try again..'), nl, start.

Output of the program:


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:

1. What is Prolog and what is it used for?


Prolog is a declarative programming language commonly used in artificial intelligence and
computational linguistics. Its name stands for "Programming in Logic." Prolog is based on
formal logic, specifically first-order predicate calculus, and it excels at symbolic
computation and symbolic reasoning tasks.
2. What is a knowledge base in Prolog and how is it represented?
In Prolog, a knowledge base is a collection of facts and rules that represent information
about a specific domain or problem. It serves as the foundation upon which Prolog
programs operate, providing the data and logical relationships necessary to answer queries
and solve problems.

3. How do you define facts and rules in Prolog?


In Prolog, facts and rules are defined using predicates, which are statements about
relationships or properties in a specific domain. Here's how you define facts and rules in
Prolog

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:

 Limited Efficiency: Prolog's execution model, based on backtracking and


exhaustive search, can lead to inefficient performance for certain types of
problems, especially those requiring complex search spaces or large data sets.
 Difficulty in Debugging: Prolog programs can be challenging to debug,
especially for beginners, due to the non-linear nature of the execution flow and
the implicit backtracking mechanism.
Artificial Intelligence (3170716) Enrollment Number: 21060116087

7. What are some real-world applications of Prolog-based knowledge bases?


 Expert Systems
 Natural Language Processing (NLP)
 Medical Diagnosis
 Intelligent Tutoring Systems
 Semantic Web

Suggested Reference:
1. http://lpn.swi-prolog.org/lpnpage.php?pageid=online

References used by the students:

Rubric wise marks obtained:

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

Implement following prolog programs.


a. To find the greatest variable among the three variables.
b. To find a factorial of a given number.
c. To check whether a given number is palindrome or not.
d. To check whether a given number is prime or not.

Date:

Competency and Practical Skills: Knowledge of logic programming, Basics of search


Techniques

Relevant CO: CO1

Objectives:To create a functional and efficient Prolog program for solving logic puzzles.

Equipment/Instruments: Personal Computer, SWI-Prolog Interpreter

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

5. Soundness and Completeness:


6. Prolog is sound, which means that if it derives a conclusion, that conclusion is guaranteed to
be true according to the rules and facts. It is also complete, meaning that it will find all valid
solutions to a query if they exist within the given knowledge base.
```
factorial(0, 1).
factorial(N, F) :- N > 0, N1 is N - 1, factorial(N1, F1), F is N * F1.
```

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.

8. Cut Operator (!):


The cut operator is used in Prolog to control the search process and prune certain branches of
the search tree. It can be used to prevent backtracking in some cases.

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).

reverse_number_helper(0, RevN, RevN).


reverse_number_helper(N, Acc, RevN) :-
N > 0,
Digit is N mod 10,
NewAcc is Acc * 10 + Digit,
NewN is N // 10,
reverse_number_helper(NewN, NewAcc, 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.

3. What is logical inference in Prolog, and how does it work?


In Prolog, logical inference refers to the process by which the Prolog engine derives
conclusions or answers from the given set of facts and rules. Prolog uses a form of logical
reasoning called backward chaining, which is based on the principle of logical deduction.

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)

References used by the students:


Rubric wise marks obtained:

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

Solve 8 Puzzle Problem using A* Algorithm in any programming Language.

Date:

Competency and Practical Skills:Knowledge of logic programming

Relevant CO: CO1

Objectives: To optimize the performance of the A* algorithm by minimizing the number of states
explored and improving the efficiency of the heuristic function.

Equipment/Instruments: Personal Computer, open-source software for programming

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.

f-score = h-score + g-score

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.

How A* solves the 8-Puzzle problem.

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.

Safety and necessary Precautions:

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 __lt__(self, other):


return (self.g + self.h) < (other.g + other.h)

def __eq__(self, other):


return self.board == other.board

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 move_blank(self, direction):


i, j = self.get_blank_position()
new_i, new_j = i, j
if direction == 'up':
new_i -= 1
elif direction == 'down':
new_i += 1
elif direction == 'left':
new_j -= 1
elif direction == 'right':
new_j += 1
if 0 <= new_i < 3 and 0 <= new_j < 3:
new_board = [row[:] for row in self.board]
new_board[i][j], new_board[new_i][new_j] = new_board[new_i][new_j], new_board[i][j]
return PuzzleState(new_board, self, direction)
return None
Artificial Intelligence (3170716) Enrollment Number: 21060116087

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)

for direction in ['up', 'down', 'left', 'right']:


next_state = current_state.move_blank(direction)
if next_state and next_state not in closed_set:
next_state.g = current_state.g + 1
next_state.h = manhattan_distance(next_state)
heapq.heappush(open_list, next_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)

References used by the students:

Rubric wise marks obtained:

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

Implement following prolog programs based on list.


a. To display first element of a list.
b. To display last element of a list.
c. To display all element of a list
d. To display elements up to specified index of a list.
e. To count number of elements in a list.
f. To count odd and even elements of a list.

Date:

Competency and Practical Skills:Understanding of basics of lists.

Relevant CO: CO1

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.

Equipment/Instruments: Personal Computer, open-source software for programming

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.

5. List Processing with Recursion:


- Recursion is a common technique for processing lists in Prolog.
- Recursive predicates can be used to traverse, modify, and perform various
operations on lists.

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

8. Lists as Knowledge Representation:


- Lists are often used to represent structured data in Prolog, such as facts, rules, and
databases.
- Lists can represent records, where each element corresponds to a field of
information.

9. List as Stacks and Queues:


- Lists can be used as stacks (Last-In, First-Out) or queues (First-In, First-Out) to
implement various data structures.

10. Error Handling and Edge Cases:


- Consideration should be given to handling empty lists and other edge cases to
ensure the robustness of Prolog programs.

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. How can you represent an empty list in Prolog?


In Prolog, an empty list can be represented as `[]` (an empty pair of square brackets). This signifies
a list with no elements. For example: empty_list([]).
This predicate `empty_list/1` would succeed if its argument is an empty list, and fail otherwise.

2. What is the "cons" operator in Prolog, and what is its symbol?


In Prolog, the "cons" operator is used to construct a new list by adding an element to the beginning
of an existing list. The cons operator is denoted by the symbol `|` (vertical bar). It's also known as
the "list constructor."

3. How do you access the first element of a list in Prolog?


In Prolog, you can access the first element of a list by using pattern matching or the built-in
predicate `nth0/3`.

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.

4. What is the purpose of the length/2 predicate in Prolog?


In Prolog, the `length/2` predicate is used to determine the length of a list or to generate lists of a
specified length.
The syntax of `length/2` is `length(List, Length)`, where `List` is a list and `Length` is an integer
representing the length of the list.
1. Determining the Length: If you provide a list as the first argument and a variable as the second
argument, Prolog will attempt to determine the length of the list and unify it with the variable.
For example:
?- length([1, 2, 3], Length).
Length = 3.

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)

References used by the students:

Rubric wise marks obtained:

Problem Understandi Completeness


Knowledge
Recognition ng and accuracy Ethics (2)
Rubrics (2) Total
(2) (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: 5

Write a prolog program to solve water jug problem.

Date:

Competency and Practical Skills: Understanding of basics of water jug problem.

Relevant CO: CO1,CO2

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.

Equipment/Instruments: Personal Computer, PROLOG software

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.

Elements of the Problem:

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.

Constraints and Rules:

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 fill a jug completely.


Artificial Intelligence (3170716) Enrollment Number: 21060116087

- You can empty a jug completely.

- 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.

Objectives and Solutions:

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:

1. Systematic Search: This approach involves systematically trying different combinations of


pouring actions to find a solution. It may use algorithms such as breadth-first search, depth-
first search, or heuristic methods to minimize the number of steps.

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.

3. Optimization: Once a solution is found, it can be further optimized to minimize the


number of steps or the amount of water wastage.

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.

Safety and necessary Precautions:

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:

1. What is the primary objective of the water jug problem?


The primary objective of the water jug problem is to determine a sequence of actions that
allows you to measure out a specific quantity of water using two jugs of known capacities.
This problem typically involves maximizing the use of available resources (the jugs) to
achieve a desired outcome, such as measuring a certain volume of water.

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)

References used by the students:

Rubric wise marks obtained:

Problem Understandi Completeness


Knowledge
Recognition ng and accuracy Ethics (2)
Rubrics (2) Total
(2) (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: 6

Implement the Minimax algorithm for a simple tic-tac-toe game using Python Language.

Date:

Competency and Practical Skills:


Basic knowledge of Python programming language, Familiarity with the rules of tic-tac-toe game,
including the board layout and winning conditions.
Understanding of the Minimax algorithm, which is a decision-making algorithm.

Relevant CO: CO3

Objectives: To illustrate how to recursively apply the Minimax algorithm to build a game tree
and determine the optimal move for the computer player.

Equipment/Instruments: Personal Computer, Python3, Jupytor Notebook

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.

Safety and necessary Precautions:

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]

# Check for draw


if all([cell != " " for row in board for cell in row]):
return "draw"

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

def minimax(board, depth, is_maximizing):


winner = check_winner(board)
Artificial Intelligence (3170716) Enrollment Number: 21060116087

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

References used by the students:

Rubric wise marks obtained:

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:

Competency and Practical Skills: Understanding of Bayesian Networks.


Familiarity with the Monty Hall problem, which is a classic probability puzzle that involves three
doors and a prize.
Knowledge of probability theory, including conditional probability and Bayes' theorem.
Familiarity with a programming language

Relevant CO: CO4

Objectives:To understand how Bayesian Networks can be used to represent and reason about
uncertain knowledge.

Equipment/Instruments: Personal Computer, Programming Language

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.

The Monty Hall problem

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

 To understand why this is the case, consider the following:


 When the player initially chooses a door, there is a 1/3 chance that they have chosen the
door with the prize, and a 2/3 chance that they have chosen a door with a goat. When the
host then opens one of the other doors to reveal a goat, the probability that the player's
initial choice was correct remains at 1/3. However, the probability that the prize is behind
the other unopened door is now 2/3.
 Therefore, when given the option to switch, the player should always switch because the
probability of winning the prize increases from 1/3 to 2/3. This may seem counterintuitive,
as it goes against our initial intuition that the probability of winning should be equally
distributed among the three doors. However, this is a classic example of how probabilities
can be counterintuitive, and why it is important to understand the underlying mathematics.

 Safety and necessary Precautions:

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;

public class MontyHallSimulation {


public static void main(String[] args) {
int numTrials = 100000;
int stayWins = 0;
int switchWins = 0;

for (int i = 0; i < numTrials; i++) {


ArrayList<Character> doors = new ArrayList<>();
doors.add('A');
doors.add('B');
doors.add('C');
Collections.shuffle(doors);
char playerChoice = doors.get(new Random().nextInt(3));
char prizeDoor = doors.get(new Random().nextInt(3));
char hostChoice = revealDoor(doors, playerChoice, prizeDoor);
char remainingDoor = switchOrStay(doors, playerChoice, hostChoice);
if (remainingDoor == prizeDoor) {
stayWins++;
} else {
switchWins++;
}
}
Artificial Intelligence (3170716) Enrollment Number: 21060116087

double stayProbability = (double) stayWins / numTrials;


double switchProbability = (double) switchWins / numTrials;

System.out.println("Probability of winning by staying: " + stayProbability);


System.out.println("Probability of winning by switching: " + switchProbability);
}

private static char revealDoor(ArrayList<Character> doors, char playerChoice, char prizeDoor)


{
for (char door : doors) {
if (door != playerChoice && door != prizeDoor) {
return door;
}
}
return ' ';
}

private static char switchOrStay(ArrayList<Character> doors, char playerChoice, char


hostChoice) {
doors.remove((Character) hostChoice);
doors.remove((Character) playerChoice);
return doors.get(0);
}
}

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

2. What are some applications of Bayesian Networks?


Bayesian Networks have a wide range of applications across various domains due to their
ability to model probabilistic relationships between variables. Some key applications of
Bayesian Networks include:
1).Medical Diagnosis and Healthcare: Bayesian Networks help doctors diagnose diseases
by modeling relationships between symptoms, patient data, and medical tests, improving
accuracy in treatment decisions.
2).Risk Assessment and Management: They assist in evaluating and mitigating risks in
finance, insurance, and engineering by modeling dependencies between variables like
market conditions and environmental factors.
3).Fraud Detection and Prevention: Used in banking and insurance, Bayesian Networks
analyze transaction data and customer behavior to detect and prevent fraudulent
activities, reducing financial losses.
4).Natural Language Processing (NLP) and Sentiment Analysis: In NLP, they model
language features and semantics to improve text classification, sentiment analysis, and
information retrieval, enhancing language understanding systems.

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:

Rubric wise marks obtained:


Problem Logic Completeness
Knowledge
Recognition Building and accuracy Ethics (2)
Rubrics (2) Total
(2) (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: 8

Demonstrate Connectionist Model using Tool.

Date:

Competency and Practical Skills:

Familiarity with neural networks, which are computational models inspired by the structure and
function of the brain.
Familiarity with a neural network tool.

Relevant CO: CO3.CO4

Objectives:Learn a tool should be selected that provides an easy-to-use interface for designing,
training, and deploying Connectionist Model.

Equipment/Instruments: Personal Computer, Connectionist Models Tool

Theory:

Connectionist Models

 In contrast to the symbolist architectures in which the mind is assumed to be a physical


symbol-processing system, connectionist systems are networks of large numbers of
interconnected “units.” Each unit can have associated with it a certain amount of
activation. Connections to other units are given explicit weights (including negative
weights).
 Activation spreads from one unit to another as a function of the weighted links. For
example, the function of a typical link might be to multiply the input activation by its
weight and then apply a threshold function. A typical unit would sum all of its input
activations, then divide this among all its links. The weights on the links are adjustable
with experience.
 Some of the links may represent sensory inputs from the outside world; some may
represent output to effectors to the outside world. Units in connectionist models are
usually taken to be below the level of a symbol. For example, different units may
represent visual features of a letter such as verticalness or roundedness.

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

Some Examples of popular tools:

 TensorFlow: An open-source platform developed by Google for building and training


machine learning models, including neural networks. It provides a high-level API that
makes it easy to build complex models with multiple layers and customizable activation
functions.
 PyTorch: An open-source machine learning library developed by Facebook that provides a
dynamic computational graph for building neural networks. It is highly optimized for GPU
acceleration and provides a Pythonic interface for building and training models.
 Keras: A high-level neural networks API developed in Python that can run on top of
TensorFlow, CNTK, or Theano. It provides a simple and intuitive interface for designing
and training neural networks, and supports both convolutional and recurrent networks.
 Caffe: A deep learning framework developed by Berkeley AI Research (BAIR) that is
optimized for speed and memory efficiency. It provides a C++ API for building and
training neural networks and supports a variety of pre-trained models for image
recognition and other tasks.
 FastAI: A Python library that provides tools for building and training deep learning
models, including neural networks, with a focus on ease of use and fast prototyping.

Safety and necessary Precautions:


Different tools are designed for different tasks, and it's crucial to use a tool that is
appropriate for the task at hand.
Procedure:
 Choose a connectionist modeling tool
 Define the problem
 Design the architecture of the
 Implement the model
 Test the model
 Deploy the model

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

# Load the MNIST dataset


(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# Preprocess the data


train_images = train_images / 255.0
test_images = test_images / 255.0

# Define the model architecture


model = Sequential([
Flatten(input_shape=(28, 28)), # Flatten the input images
Dense(128, activation='relu'), # Fully connected layer with 128 neurons
Dense(10, activation='softmax') # Output layer with 10 neurons (one for each digit)
])

# Compile the model


model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

# Train the model


model.fit(train_images, train_labels, epochs=5)

# Evaluate the model on test data


test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f'Test accuracy: {test_acc}')

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:

1. What is the role of the activation function in a connectionist model?


The activation function plays a crucial role in a connectionist model, specifically in
artificial neural networks (ANNs). Its primary role is to introduce non-linearity into the
output of each neuron in the network. Here's a breakdown of its roles

2. What is the purpose of testing a connectionist model?


 Evaluate Performance
 Detect Overfitting
 Tune Hyperparameters
 Assess Model Robustness
 Compare Models
 Validate Assumptions
3. What is back propagation in a connectionist model?
Backpropagation is a key algorithm used to train connectionist models, specifically
artificial neural networks (ANNs). It is a method for adjusting the weights of the
connections between neurons in the network in order to minimize the error between the
predicted outputs and the true targets.

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

References used by the students:


Rubric wise marks obtained:

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

Implement Genetic Algorithm in any Programming Language.

Date:

Competency and Practical Skills:

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

Relevant CO: CO4

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.

GA works by maintaining a population of candidate solutions (also called chromosomes) and


applies genetic operators such as selection, crossover, and mutation to create new and hopefully
better solutions. The basic idea is to mimic the natural process of evolution and survival of the
fittest in order to find the optimal solution to a problem.

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).

Safety and necessary Precautions:

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;

public Individual(int size) {


genes = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < size; i++) {
genes.add(rand.nextInt(2));
}
calculateFitness();
}

public void setGenes(List<Integer> genes) {


this.genes = genes;
calculateFitness();
}
Artificial Intelligence (3170716) Enrollment Number: 21060116087

private void calculateFitness() {


int target = 20;
int sum = 0;
for (int gene : genes) {
sum += gene;
}
fitness = Math.abs(target - sum);
}

public int getFitness() {


return fitness;
}

public List<Integer> getGenes() {


return genes;
}
}

public class GeneticAlgorithm {


private static final int POPULATION_SIZE = 100;
private static final int NUM_GENES = 10;
private static final double MUTATION_RATE = 0.1;
private static final int NUM_GENERATIONS = 50;

private static Individual tournamentSelection(List<Individual> population, int tournamentSize)


{
Collections.shuffle(population);
Individual bestIndividual = population.get(0);
for (int i = 1; i < tournamentSize; i++) {
Individual individual = population.get(i);
if (individual.getFitness() < bestIndividual.getFitness()) {
bestIndividual = individual;
}
}
return bestIndividual;
}

private static Individual[] crossover(Individual parent1, Individual parent2) {


Random rand = new Random();
int crossoverPoint = rand.nextInt(NUM_GENES);
List<Integer> child1Genes = new ArrayList<>(parent1.getGenes().subList(0,
crossoverPoint));
child1Genes.addAll(parent2.getGenes().subList(crossoverPoint, NUM_GENES));
List<Integer> child2Genes = new ArrayList<>(parent2.getGenes().subList(0,
crossoverPoint));
child2Genes.addAll(parent1.getGenes().subList(crossoverPoint, NUM_GENES));
Individual child1 = new Individual(NUM_GENES);
child1.setGenes(child1Genes);
Individual child2 = new Individual(NUM_GENES);
Artificial Intelligence (3170716) Enrollment Number: 21060116087

child2.setGenes(child2Genes);
return new Individual[]{child1, child2};
}

private static void mutate(Individual individual, double mutationRate) {


Random rand = new Random();
List<Integer> genes = individual.getGenes();
for (int i = 0; i < NUM_GENES; i++) {
if (rand.nextDouble() < mutationRate) {
genes.set(i, 1 - genes.get(i)); // Flip the bit
}
}
individual.setGenes(genes);
}

public static Individual geneticAlgorithm() {


List<Individual> population = new ArrayList<>();
for (int i = 0; i < POPULATION_SIZE; i++) {
population.add(new Individual(NUM_GENES));
}
for (int generation = 1; generation <= NUM_GENERATIONS; generation++) {
List<Individual> newPopulation = new ArrayList<>();
for (int i = 0; i < POPULATION_SIZE / 2; i++) {
Individual parent1 = tournamentSelection(population, 5);
Individual parent2 = tournamentSelection(population, 5);
Individual[] children = crossover(parent1, parent2);
mutate(children[0], MUTATION_RATE);
mutate(children[1], MUTATION_RATE);
newPopulation.add(children[0]);
newPopulation.add(children[1]);
}
population = newPopulation;
Individual bestIndividual = Collections.min(population, (ind1, ind2) ->
Integer.compare(ind1.getFitness(), ind2.getFitness()));
System.out.println("Generation " + generation + ": Best Solution: " +
bestIndividual.getGenes() + ", Fitness: " + bestIndividual.getFitness());
}
return Collections.min(population, (ind1, ind2) -> Integer.compare(ind1.getFitness(),
ind2.getFitness()));
}

public static void main(String[] args) {


Individual bestSolution = geneticAlgorithm();
System.out.println("Best solution found: " + bestSolution.getGenes());
}
}
Artificial Intelligence (3170716) Enrollment Number: 21060116087

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

evaluate them sequentially or in parallel?


Each individual's fitness in the population is evaluated sequentially using the
fitness_score function, which compares the individual's similarity to the target solution.
While sequential evaluation is straightforward, for larger populations or complex fitness
evaluations, parallel evaluation methods may be beneficial for scalability and reduced
computation time.

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

References used by the students:

Rubric wise marks obtained:

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

Write a prolog program to solve Tower of Hanoi problem.

Date:

Competency and Practical Skills:

Knowledge of basic PROLOG syntax

Relevant CO: CO3,CO4

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.

Equipment/Instruments: Personal Computer, SWI-Prolog Interpreter

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:

1. Pegs: There are three pegs: A, B, and C.

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.

Theoretical Aspects of the Tower of Hanoi:

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.

Safety and necessary Precautions:

The program should handle exceptions, such as input errors or invalid operations.

Procedure:

Observation/Program:

hanoi(1, Start, _, End) :-


write('Move top disk from '), write(Start),
write(' to '), write(End), nl.

hanoi(N, Start, Center, End) :-


N > 1,
M is N - 1,
hanoi(M, Start, End, Center),
hanoi(1, Start, _, End),
hanoi(M, Center, Start, End).

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:

1. Introduction to Recursion: The Tower of Hanoi problem provides a classic example of a


problem that can be elegantly solved using recursion. It helps students understand the
concept of recursion, including base cases and recursive calls.

2. Understanding Algorithms: It helps students understand and analyze algorithms,


including their time complexity and efficiency. The problem highlights the importance of
developing efficient algorithms to solve real-world problems.

3. Developing Problem-Solving Skills: The problem encourages students to think critically


and creatively to find solutions. It fosters the development of problem-solving skills,
logical reasoning, and strategic thinking.

4. Mathematical Concepts: The Tower of Hanoi problem is closely related to various


mathematical concepts, including number theory, combinatorics, and graph theory. It
provides a practical application for these concepts and reinforces their understanding.

5. Computational Thinking: It promotes computational thinking by breaking down


complex problems into smaller, more manageable subproblems. Students learn to analyze
problems, design algorithms, and implement solutions systematically.

6. Interactive Learning: The problem can be used in interactive learning environments,


such as programming exercises or hands-on activities using physical Tower of Hanoi sets.
This enhances student engagement and participation.

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:

Rubrics Knowledge Problem Logic Tool Usage Ethics (2) Total


(2) Recognition Building (2)
Artificial Intelligence (3170716) Enrollment Number: 21060116087

(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

You might also like