CS1503 AI Lab
CS1503 AI Lab
of CSE
2023 - 2024
Aim:
Algorithm:
Step 1: Define a list OPEN. Initially, open consists solely of a single node, the
start node S.
Step 3: Remove node n with the smallest value of f(n) from OPEN and move it
to list CLOSED. If node n is a goal state, return success and exit.
Step 5: If any successor to n is the goal node, return success and the solution
by tracing the path from goal node to S. Otherwise, go to Step-06.
Program:
class Solution:
def solve(self, board):
dict = {}
flatten = []
for i in range(len(board)):
flatten += board[i]
flatten = tuple(flatten)
dict[flatten] = 0
if flatten == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return 0
1
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
return self.get_paths(dict)
def get_paths(self, dict):
cnt = 0
while True:
current_nodes = [x for x in dict if dict[x] == cnt]
if len(current_nodes) == 0:
return -1
for node in current_nodes:
next_moves = self.find_next(node)
for move in next_moves:
if move not in dict:
dict[move] = cnt + 1
if move == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return cnt + 1
cnt += 1
def find_next(self, node):
moves = {
0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4, 6],
4: [1, 3, 5, 7],
5: [2, 4, 8],
6: [3, 7],
7: [4, 6, 8],
8: [5, 7],
}
results = []
pos_0 = node.index(0)
for move in moves[pos_0]:
new_node = list(node)
new_node[move], new_node[pos_0] = new_node[pos_0],
new_node[move]
2
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
results.append(tuple(new_node))
return results
ob = Solution()
matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0]
]
print(ob.solve(matrix))
Output:
Result:
Thus the 8-puzzle problem was written, executed and verified successfully.
Aim:
3
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Algorithm:
Step 2: First we will fill the 4 litre jug completely with water.
Step 3: Then optimal approach would be to empty water from 4-litre jug into 3-
litre.
Step 5: Pour the water from 4L jug into 3L jug now 4L container is completely
empty and 1L water in present in 3L litre jug.
Step 7:- On transferring water from 4L jug to 3L jug, we will get 2L water in 4L
jug which was our required quantity.
Program:
4
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Aim:
To write a python program for a path search problem to find a path from point
A to point B using A* Search Algorithm.
5
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Algorithm:
Step 2: For all the neighbouring nodes, find the least cost F node.
Step 3.2.1: If the node is not on the open list, move it to the open
list and calculate f, g, h.
Step3.2.2: If the node is on the open list, check if the path it offers
is less than the current path and change to it if it does so.
Program:
6
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
7
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None
#for simplicity we ll consider heuristic distances given
#and this function returns heuristic distance for all nodes
def heuristic(n):
H_dist = {
'A': 11,
'B': 6,
'C': 99,
'D': 1,
'E': 7,
'G': 0,
}
return H_dist[n]
#Describe your graph here
Graph_nodes = {
'A': [('B', 2), ('E', 3)],
'B': [('C', 1),('G', 9)],
'C': None,
'E': [('D', 6)],
'D': [('G', 1)],
}
aStarAlgo('A', 'G')
Output:
Result:
Aim:
Algorithm:
8
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Step 1: Evaluate the initial state, if it is goal state then return success and
Stop.
Step 2: Loop Until a solution is found or there is no new operator left to apply.
Step 5: Exit.
Step 1: Evaluate the initial state, if it is goal state then return success and
stop, else make current state as initial state.
Step 2: Loop until a solution is found or the current state does not change.
Step 3: Let SUCC be a state such that any successor of the current state will
be better than it.
Step 5: Exit.
Program:
import random
def randomSolution(tsp):
cities = list(range(len(tsp)))
solution = []
9
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
for i in range(len(tsp)):
randomCity = cities[random.randint(0, len(cities) - 1)]
solution.append(randomCity)
cities.remove(randomCity)
return solution
def getNeighbours(solution):
neighbours = []
for i in range(len(solution)):
for j in range(i + 1, len(solution)):
neighbour = solution.copy()
neighbour[i] = solution[j]
neighbour[j] = solution[i]
neighbours.append(neighbour)
return neighbours
def hillClimbing(tsp):
currentSolution = randomSolution(tsp)
currentRouteLength = routeLength(tsp, currentSolution)
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength =
getBestNeighbour(tsp, neighbours)
10
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
def main():
tsp = [
[0, 400, 500, 300],
[400, 0, 300, 500],
[500, 300, 0, 400],
[300, 500, 400, 0]
]
print(hillClimbing(tsp))
if __name__ == "__main__":
main()
Output:
Result:
Thus the Hill Climbing problem was written, executed and verified
successfully.
Create a First Order Logic solver.
Aim:
11
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Algorithm:
Step 2: Takes a FOL statement as input and extracts the predicates and their
arguments using regular expressions.
Step 6: Checks if the predicates in the statement exist in the facts, performs
argument substitution, and adds any new predicates to the facts with an
empty list as the value.
Step 8: Call evaluate_fol(statement, facts) with the desired FOL statement and
the facts dictionary.
Program:
import re
# Function to parse a FOL statement into predicates and arguments
def parse_fol(statement):
pattern = r'([A-Za-z]+\([^)]*\))'
predicates = re.findall(pattern, statement)
arguments = [re.findall(r'\w+', pred) for pred in predicates]
return predicates, arguments
# Function to evaluate a FOL statement
def evaluate_fol(statement, facts):
predicates, arguments = parse_fol(statement)
for pred, args in zip(predicates, arguments):
pred_parts = pred.split('(')
pred_name = pred_parts[0]
12
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
pred_args = pred_parts[1].rstrip(')').split(',')
if pred_name in facts:
fact_args = facts[pred_name]
if len(args) == len(fact_args):
substitution = {arg: fact_arg for arg, fact_arg in zip(args, fact_args)}
substituted_pred_args = [substitution.get(arg, arg) for arg in
pred_args]
substituted_pred = f"{pred_name}
({','.join(substituted_pred_args)})"
if substituted_pred not in facts:
facts[substituted_pred] = []
else:
facts[pred] = []
# Example usage
facts = {
'Person(John)': [],
'Person(Mary)': [],
'Likes(John, IceCream)': [],
'Likes(Mary, Chocolate)': []
}
statement = 'Likes(x, IceCream)'
evaluate_fol(statement, facts)
print(facts)
Output:
{
'Person(John)': [],
'Person(Mary)': [],
'Likes(John, IceCream)': [],
'Likes(Mary, Chocolate)': [],
'Likes(x, IceCream)': []
}
Result:
Thus the first order logic problem was written, executed and verified
successfully.
Aim:
13
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Algorithm:
Step 4: Inside the inference engine function, iterate until no new facts can be
inferred.
Step 5: Set a flag to track if a new fact was added in the current iteration.
Step 6: Iterate over each rule.
Step 8: If the rule is applicable and its conclusion is not already a fact.
Step 10: Set the flag to indicate that a new fact was added.
Step 11: Print the applied rule and the updated facts.
Step 12: If no new fact was added in the iteration, break the loop.
Step 13: Call the forward chaining inference engine function with the initial
rules and facts.
Program:
14
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Output:
15
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Result:
Thus the forward chaining inference engine problem was written, executed
and verified successfully.
Aim:
16
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Algorithm:
Step 1: Define the Vacuum Cleaner Agent class with the following methods:
Step 3: Define the initial state of the rooms, represented by a list of Boolean
values (True for clean, False for dirty).
Step 4: Repeat the following steps until all rooms are clean:
Program
class VacuumCleanerAgent:
def __init__(self):
self.location = 0 # 0 represents Room A, and 1 represents Room B
17
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
def main():
agent = VacuumCleanerAgent()
# Define the initial state of the rooms (True represents clean, False
represents dirty)
rooms = [True, False]
if action == 'clean':
rooms[current_location] = agent.clean(current_location)
elif action == 'move' or action == 'move_back':
18
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
agent.act(action)
if __name__ == "__main__":
main()
Result:
Thus the Simple Agent for the Vacuum-Cleaner world problem was written,
executed and verified successfully.
19
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Aim:
Algorithm:
Step 1: Create a 3x3 grid to represent the Tic Tac Toe board.
Step 5: Inside the play_game() function: a. Initialize the board and set the
current player as "X". b. Run a loop until the game is over.
Step 7: Prompt the current player to enter the row and column for their move.
Step 8: Validate the move and update the board with the player's mark.
Step 10: Check if the current player has won using check_winner(board).
Step 11: If there is a winner, print the board and the winning player.
Step 13: Check if the game is a draw (moves == 9). 1. If it is a draw, print the
board and announce the draw. 2. Break the loop and end the game.
Step 14: Switch the current player to the other player ("X" to "O" or vice
versa).
Step 15: Call the play_game() function to start the Tic Tac Toe game.
Program:
20
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
21
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Output:
| |
-----------
| |
-----------
| |
22
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
O|X|
-----------
X|X|
-----------
| |
Player X wins!
Result:
Thus the Tic Tac Toe game problem was written, executed and verified
successfully.
Aim:
Algorithm:
23
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Step 6: If the command is 'right', update the turtle's heading by turning it right
by the given angle.
Step 7: If the command is 'left', update the turtle's heading by turning it left by
the given angle.
Step 8: After executing all the movement commands, display the final position
and heading of the turtle.
Program:
import turtle
# Create a turtle object
my_turtle = turtle.Turtle()
# Move the turtle forward
my_turtle.forward(100)
# Rotate the turtle left by 90 degrees
my_turtle.left(90)
# Move the turtle forward again
my_turtle.forward(100)
# Rotate the turtle right by 45 degrees
my_turtle.right(45)
# Move the turtle backward
my_turtle.backward(100)
# Hide the turtle
my_turtle.hideturtle()
# Close the turtle graphics window
turtle.done()
Output:
24
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Result:
Thus the Turtle moving problem was written, executed and verified
successfully.
Aim:
Algorithm:
25
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Step 11: Prompt the current player to enter their move (row and column).
Step 14: If there is a winner, print the winner and end the game.
Step 16: If the board is full, print that it's a draw and end the game.
Program:
26
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
def print_board(board):
# Print the current state of the game board
for row in board:
print(row)
def is_board_full(board):
# Check if the game board is full
for row in board:
if 0 in row:
return False
return True
def make_move(board, row, col, player):
# Make a move on the game board
if board[row][col] == 0:
board[row][col] = player
return True
else:
return False
def check_winner(board):
# Check if there is a winner
for i in range(3):
# Check rows
if board[i][0] == board[i][1] == board[i][2] != 0:
return board[i][0]
# Check columns
if board[0][i] == board[1][i] == board[2][i] != 0:
return board[0][i]
# Check diagonals
if board[0][0] == board[1][1] == board[2][2] != 0:
return board[0][0]
if board[0][2] == board[1][1] == board[2][0] != 0:
return board[0][2]
# No winner
return 0
# Simulate the game playing
# Initialize the game board
board = initialize_board()
current_player = 1
# Main game loop
while True:
# Print the current state of the board
print_board(board)
# Prompt the current player to make a move
row = int(input("Enter the row (0-2): "))
col = int(input("Enter the column (0-2): "))
27
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
Output:
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
Enter the row (0-2): 1
Enter the column (0-2): 1
[0, 0, 0]
[0, 1, 0]
[0, 0, 0]
Enter the row (0-2): 0
Enter the column (0-2): 0
[2, 0, 0]
[0, 1, 0]
[0, 0, 0]
Enter the row (0-2): 1
Enter the column (0-2): 2
[2, 0, 0]
[0, 1, 1]
[0, 0, 0]
Enter the row (0-2): 2
Enter the column (0-2): 2
[2, 0, 0]
[0, 1, 1]
[0, 0, 2]
Enter the row (0-2): 2
Enter the column (0-2): 0
[2, 0, 0]
28
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024
[0, 1, 1]
[1, 0, 2]
Enter the row (0-2): 0
Enter the column (0-2): 2
[2, 0, 1]
[0, 1, 1]
[1, 0, 2]
Enter the row (0-2): 0
Enter the column (0-2): 1
[2, 2, 1]
[0, 1, 1]
[1, 0, 2]
Enter the row (0-2): 1
Enter the column (0-2): 0
[2, 2, 1]
[1, 1, 1]
[1, 0, 2]
Player 1 wins!
Result:
Thus the Simulation of Game playing problem was written, executed and
verified successfully.
29