0% found this document useful (0 votes)
21 views21 pages

Ai Ass 1

The document is an assignment submission by Haider Ali for an Artificial Intelligence course, detailing the creation of various types of agents in a grid-based environment using Python. It includes implementations for a simple agent, a cleaning agent, a model-based agent, a utility-based agent, and a learning agent, each with specific functionalities and improvements. The assignment demonstrates the application of AI concepts through coding exercises that simulate agent behaviors in cleaning tasks.

Uploaded by

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

Ai Ass 1

The document is an assignment submission by Haider Ali for an Artificial Intelligence course, detailing the creation of various types of agents in a grid-based environment using Python. It includes implementations for a simple agent, a cleaning agent, a model-based agent, a utility-based agent, and a learning agent, each with specific functionalities and improvements. The assignment demonstrates the application of AI concepts through coding exercises that simulate agent behaviors in cleaning tasks.

Uploaded by

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

Assignment - 01

Artificial Intelligence

SUBMITTED BY Haider Ali

SUBMITTED TO Dr. Shahnawaz Qureshi

REGISTRATION NO. B23F0001AI054


Registration No : B23F0001AI054

Question 01:
Simple Agent Creation
Objective: Create a simple agent that can perform actions in a predefined environment.
• Define the Environment: Create a grid-based environment where the agent can move.
• Implement the Agent: Create an agent that can move up, down, left, or right.
• Display the Environment: Write a function to display the current state of the environment and the
agent's position.

• Move the Agent: Implement a method to move the agent based on user input.
Code:
• Python program:
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01

class GridEnvironment:
def __init__(self, size):
self.size = size self.agent_pos = [0, 0]
# Starting position at top-left

def display(self): for i


in range(self.size): for
j in range(self.size):
if [i, j] == self.agent_pos:
print("A", end=" ") # Agent
position else:
print(".", end=" ") #
Empty space print()
print()

def move(self, direction):

if direction == "up" and self.agent_pos[0] > 0:


self.agent_pos[0] -= 1 elif direction ==
"down" and self.agent_pos[0] < self.size - 1:
self.agent_pos[0] += 1 elif
direction == "left" and self.agent_pos[1] > 0:
self.agent_pos[1] -= 1 elif direction ==
"right" and self.agent_pos[1] < self.size - 1:
self.agent_pos[1] += 1

env = GridEnvironment(5)
while True:
env.display() move = input("Enter move (up/down/left/right) or
(shutdown) to shutdown: ").lower() if move in ["up", "down", "left",
"right"]:
env.move(move)
elif move=="shutdown":
print("Shutting down...")
break else:
print("Invalid move, try again.")

Registration No : B23F0001AI054

This GridEnvironment class represents a 5x5 grid where an agent (A) moves based on user input. The agent
starts at the top-left corner (0,0) and can move up, down, left, or right within the grid's boundaries. The

Page|2
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
environment updates and displays the agent's position after each move. The program runs in a loop, accepting
movement commands until the user enters "shutdown" to exit.

Screenshot of the Output:

Registration No : B23F0001AI054

Question 02:

Page|3
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Simple Reflex Agent
• Define an agent that reacts to dirt in an environment.
• Simulate an environment with randomly placed dirt.
• Make the agent clean the environment.

Code:
Python program

import random

class CleaningEnvironment:
def __init__(self, size):
self.size = size
self.agent_pos = [0, 0]
self.grid = [[random.choice(["D", "."]) for _ in range(size)] for _ in
range(size)]

def display(self):
for i in range(self.size):
for j in range(self.size):
if [i, j] == self.agent_pos:
print("A", end=" ")
else:
print(self.grid[i][j], end=" ")
print()
print()

def clean(self):
x, y = self.agent_pos
if self.grid[x][y] == "D":
self.grid[x][y] = "."
print(f"Cleaned at ({x}, {y})!")

def move(self): for i


in range(self.size):
Registration No : B23F0001AI054
for j in range(self.size): self.agent_pos = [i, j] print(f"Moving to ({i}, {j})")
self.display()
self.clean()

env = CleaningEnvironment(3) env.move()

Page|4
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
This CleaningEnvironment class simulates a simple vacuum cleaner agent in a 3x3 grid.
The grid randomly contains dirty spots ("D") and clean spots ("."). The agent:
1. Starts at (0,0).
2. Moves through every cell in the grid, row by row.
3. Cleans any dirty spot ("D") it encounters.
4. Displays the grid at each step.

Screenshot of the Output:


Registration No : B23F0001AI054

Page|5
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01

Registration No : B23F0001AI054

Question 03:
Model-Based Agent
•Modify the previous agent to store a history of cleaned positions.
•Ensure it does not clean the same position twice unnecessarily.
•Keep track of the environment's current state and update accordingly.

Code:
•Python program:

Page|6
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
import random

class
CleaningEnvironment:
def __init__(self, size):
self.size = size
self.agent_pos = [0, 0]
self.grid = [[random.choice(["D", "."]) for _ in range(size)] for _ in range(size)]
self.cleaned_positions = set()

def display(self): for i


in range(self.size): for
j in range(self.size):
if [i, j] == self.agent_pos:
print("A", end=" ")
else:
print(self.grid[i][j], end=" ")
print()
print()

def clean(self): x, y = self.agent_pos if


self.grid[x][y] == "D" and (x, y) not in
self.cleaned_positions:
self.grid[x][y] = "."
self.cleaned_positions.add((x, y))
print(f"Cleaned at ({x}, {y})!")

def move(self): for i in


range(self.size): for j in
range(self.size):
self.agent_pos = [i, j]
print(f"Moving to ({i}, {j})")
self.display()
self.clean()

env = CleaningEnvironment(3)
env.move()

Registration No : B23F0001AI054

This Python program simulates a cleaning robot operating in a grid-based environment.


The grid is initialized with random dirty spots ("D") and clean spots ("."), and the robot
starts at the top-left corner. It moves systematically through each cell, row by row,
displaying the grid at every step. If the robot encounters a dirty spot, it cleans it and
marks it as cleaned. The program provides a real-time view of the robot's movement and
cleaning progress, ensuring that all dirty spots are addressed efficiently. This simple
simulation demonstrates basic AI-like behavior in an automated cleaning system.

Screenshot of the Output:


Page|7
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01

Registration No : B23F0001AI054

Page|8
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01

Question 04:
Utility-Based Agent
•Define an agent that maximizes cleaning efficiency.
•Introduce a cost for movement and cleaning.

•Make the agent select actions to optimize utility


Code:
•Python program:

import random

class
CleaningEnvironment:
def __init__(self, size):
self.size = size
self.agent_pos = [0, 0]
self.grid = [[random.choice(["D", "."]) for _ in range(size)] for _ in
range(size)] self.cleaned_positions = set()
self.utility = 0

Page|9
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
self.moves = 0

def display(self):
for i in range(self.size):
for j in range(self.size):
Registration No : B23F0001AI054
if [i, j] ==
self.agent_pos:
print("A", end=" ")
else:
print(self.grid[i][j], end=" ")
print()
print(f"Utility: {self.utility}\n")

def clean(self): x, y = self.agent_pos if


self.grid[x][y] == "D" and (x, y) not in
self.cleaned_positions:
self.grid[x][y] = "."
self.cleaned_positions.add((x, y))
self.utility += 10
print(f"Cleaned at ({x}, {y})! (+10 Utility)")

def find_nearest_dirt(self):
min_distance = float("inf")
nearest_dirt = None
x, y = self.agent_pos

for i in range(self.size): for j in range(self.size):


if self.grid[i][j] == "D" and (i, j) not in self.cleaned_positions:
distance = abs(i - x) +
abs(j - y) if distance <
min_distance:
min_distance = distance
nearest_dirt = (i, j)

return nearest_dirt

def move(self):
while True:
self.display() dirt_pos =
self.find_nearest_dirt() if dirt_pos is None:
print("All dirt cleaned! Final Utility:", self.utility)
break

self.agent_pos = list(dirt_pos)
self.moves += 1
self.utility -= 1 print(f"Moving to
{dirt_pos} (-1 Utility)")
self.clean()

env = CleaningEnvironment(5)
env.move()

This Python program simulates an intelligent cleaning robot navigating a grid-based


environment. The grid is randomly initialized with clean (".") and dirty ("D") spots, and
P a g e | 10
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
the robot starts at the top-left corner. The robot systematically searches for the nearest
dirty spot, moves toward it while tracking its steps, and cleans it upon arrival. A utility
system is implemented, where cleaning increases the score while movement decreases
it. The program continuously updates the grid's state and displays the robot's progress.
The simulation runs until all dirt is cleaned, demonstrating basic AI behavior in an
automated cleaning system.

Registration No : B23F0001AI054

Screenshot of the Output:

Registration No : B23F0001AI054

P a g e | 11
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01

Question 04:
Learning Agent
•Implement an agent that learns from past experiences.
•Store previously cleaned positions and avoid redundant cleaning. • Improve
efficiency over multiple runsCode:
•Python program:

import random

P a g e | 12
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
class CleaningEnvironment:

P a g e | 13
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Registration No : B23F0001AI054

P a g e | 14
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
def __init__(self, size):
self.size = size
self.agent_pos = [0, 0]
self.total_utility = 0
self.total_moves = 0

def reset_environment(self):
"""Resets the grid and tracking data for a fresh round."""
self.grid = [[random.choice(["D", "."]) for _ in range(self.size)] for _ in range(self.size)]
self.cleaned_positions = set()
self.known_dirty_spots = {(i, j) for i in range(self.size) for j in range(self.size) if
self.grid[i][j] == "D"} self.utility = 0 self.moves = 0
self.agent_pos = [0, 0]

def display(self):
"""Displays the grid and agent
position.""" for i in range(self.size):
for j in range(self.size): if [i, j]
== self.agent_pos:
print("A", end=" ") else:
print(self.grid[i][j], end=" ")
print()
print(f"Utility: {self.utility}, Moves: {self.moves}\n")

def clean(self):
"""Cleans dirt at the agent's
position.""" x, y = self.agent_pos
if self.grid[x][y] == "D":
self.grid[x][y] = "."
self.cleaned_positions.add((x, y))
self.known_dirty_spots.discard((x, y))
self.utility += 10
print(f"Cleaned at ({x}, {y})! (+10 Utility)")

def find_nearest_dirt(self):
"""Finds the closest dirt location using Manhattan
distance.""" min_distance = float("inf")
nearest_dirt = None x, y = self.agent_pos

for i, j in
self.known_dirty_spots:
distance = abs(i - x) + abs(j - y)
if distance < min_distance:
min_distance = distance
nearest_dirt = (i, j)

return nearest_dirt

def move(self):
"""Moves the agent towards the nearest dirt until all are
cleaned.""" while self.known_dirty_spots:
self.display() dirt_pos = self.find_nearest_dirt()
if dirt_pos is None: print("All dirt cleaned! Final
Utility:", self.utility) break

self.agent_pos = list(dirt_pos)
self.moves += 1

P a g e | 15
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Registration No : B23F0001AI054
self.utility -= 1
print(f"Moving to {dirt_pos} (-1 Utility)")
self.clean()

def run_multiple_rounds(self, rounds):


"""Runs the cleaning process for multiple
rounds.""" for r in range(rounds):
print(f"\n=== Round {r + 1} ===")
self.reset_environment() # Reset at the START of each round
self.move()

# Track total performance across rounds


self.total_utility += self.utility
self.total_moves += self.moves

print(f"End of Round {r + 1}: Utility = {self.utility}, Moves =


{self.moves}")

print(f"\nTotal Utility after {rounds} rounds: {self.total_utility}")


print(f"Total Moves after {rounds} rounds: {self.total_moves}")

# Run for 2 rounds env =


CleaningEnvironment(4)
env.run_multiple_rounds(2
)

This Python program simulates a cleaning robot in a grid-based environment, running


multiple rounds of operation. The grid contains randomly placed dirt ("D") and clean
spots ("."), and the robot starts at the top-left corner. Each round, the environment
resets with new dirt positions, and the robot systematically finds and moves to the
nearest dirty spot, cleaning it while tracking movements and utility. Utility increases
when cleaning (+10) and decreases with movement (-1). The program collects total
utility and moves across multiple rounds to assess performance, making it a simple yet
effective simulation of autonomous cleaning behavior.

Screenshot of the Output:

P a g e | 16
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Registration No : B23F0001AI054

P a g e | 17
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01

P a g e | 18
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Registration No : B23F0001AI054

Registration No : B23F0001AI054

P a g e | 19
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01

P a g e | 20
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Registration No : B23F0001AI054

P a g e | 21

You might also like