CS1503 AI Lab-1
CS1503 AI Lab-1
Aim:
To write a python program to solve the 8-puzzle problem, this consists of a 3×3 board
with eight numbered tiles and a blank space.
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:
5
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE 2023 - 2024
To write a python program for a path search problem to find a path from point A to point
B using A* Search Algorithm.
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
else:
for (m, weight) in get_neighbors(n):
#nodes 'm' not in first and last set are added to first
#n is set its parent
if m not in open_set and m not in closed_set:
open_set.add(m)
parents[m] = n
g[m] = g[n] + weight
#for each node m,compare its distance from start i.e g(m) to the
#from start through n node
else:
if g[m] > g[n] + weight:
#update g(m)
g[m] = g[n] + weight
#change parent of m to n
parents[m] = n
#if m in closed set,remove and add to open
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
if n == None:
print('Path does not exist!')
return None
# if the current node is the stop_node
# then we begin reconstructin the path from it to the start_node
if n == stop_node:
path = []
while parents[n] != n:
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
print('Path found: {}'.format(path))
return path
# remove n from the open_list, and add it to closed_list
# because all of his neighbors were inspected
open_set.remove(n)
closed_set.add(n)
print('Path does not exist!')
return None
#define fuction to return neighbor and its distance
#from the passed node
def get_neighbors(v):
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:
Thus the A* searching problem was written, executed and verified successfully.
Ex. No. 4 HILL CLIMBING SEARCH ALGORITHM Date:
Aim:
To write a python program to implement Hill Climbing Search Algorithm, to find the
solution for a Travelling Salesman Problem.
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 = []
for i in range(len(tsp)):
randomCity = cities[random.randint(0, len(cities) - 1)]
9
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE 2023 - 2024
solution.append(randomCity)
cities.remove(randomCity)
return solution
def routeLength(tsp, solution):
routeLength = 0
for i in range(len(solution)):
routeLength += tsp[solution[i - 1]][solution[i]]
return routeLength
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 getBestNeighbour(tsp, neighbours):
bestRouteLength = routeLength(tsp, neighbours[0])
bestNeighbour = neighbours[0]
for neighbour in neighbours:
currentRouteLength = routeLength(tsp, neighbour)
if currentRouteLength < bestRouteLength:
bestRouteLength = currentRouteLength
bestNeighbour = neighbour
return bestNeighbour, bestRouteLength
def hillClimbing(tsp):
currentSolution = randomSolution(tsp)
currentRouteLength = routeLength(tsp, currentSolution)
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength =
getBestNeighbour(tsp, neighbours)
while bestNeighbourRouteLength < currentRouteLength:
currentSolution = bestNeighbour
currentRouteLength = bestNeighbourRouteLength
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength =
getBestNeighbour(tsp, neighbours)
return currentSolution, currentRouteLength
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:
Algorithm:
Step 2: Takes a FOL statement as input and extracts the predicates and their arguments
using regular expressions.
11
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE 2023 - 2024
evaluate_fol(statement, facts):
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 7: Create an initial dictionary of facts with some pre-defined predicates and empty
lists as values.
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]
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] = []
12
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE 2023 - 2024
# 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:
Algorithm:
Step 1: Implement a function to check if a rule is applicable based on the current facts.
Step 2: Implement a function to apply a rule by adding its conclusion to the facts if the
rule is applicable.
13
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE 2023 - 2024
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:
Result:
Thus the forward chaining inference engine problem was written, executed and verified
successfully.
15
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE 2023 - 2024
Ex. No.7 Simple Agent for the Vacuum-Cleaner world problem Date:
Aim:
To develop a Simple Agent for the Vacuum-Cleaner world problem using python
Algorithm:
Step 1: Define the Vacuum Cleaner Agent class with the following methods:
16
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE 2023 - 2024
act: Accept the chosen action as input and perform the corresponding action, i.e.,
change the agent's location if it's a movement action.
Step 2: Initialize the agent.
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':
agent.act(action)
if __name__ == "__main__":
main()
Result:
Thus the Simple Agent for the Vacuum-Cleaner world problem was written, executed
and verified successfully.
18
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 2: Define a function print_board(board) to display the current state of the board.
Step 3: Define a function check_winner(board) to check if any player has won the game.
The function checks for winning conditions in rows, columns, and diagonals.
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.
19
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE 2023 - 2024
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
return None
# Function to play the Tic Tac Toe game
def play_game():
board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
current_player = "X"
moves = 0
while True:
print_board(board)
# Get player's move
while True:
row = int(input("Enter the row (0-2): "))
col = int(input("Enter the column (0-2): "))
if 0 <= row <= 2 and 0 <= col <= 2 and board[row][col] == " ":
board[row][col] = current_player
break
else:
print("Invalid move. Try again.")
moves += 1
# Check if the current player has won
winner = check_winner(board)
if winner:
print_board(board)
print(f"Player {winner} wins!")
break
# Check if the game is a draw
if moves == 9:
print_board(board)
print("It's a draw!")
break
# Switch to the other player
current_player = "O" if current_player == "X" else "X"
# Play the Tic Tac Toe game
play_game()
Output:
| |
-----------
| |
-----------
| |
21
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE 2023 - 2024
22
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE 2023 - 2024
X|X|
-----------
X| |
Player X wins!
Result:
Thus the Tic Tac Toe game problem was written, executed and verified successfully.
Aim:
Algorithm:
Step 2: Define a list of movement commands, where each command consists of a keyword
(e.g., 'forward', 'backward', 'right', 'left') and a value representing the distance or angle.
Step 5: If the command is 'backward', update the turtle's position by moving it backward
by the given distance in the current heading direction.
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.
23
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE 2023 - 2024
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:
Result:
Thus the Turtle moving problem was written, executed and verified successfully.
24
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE 2023 - 2024
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 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): "))
# Make the move
if make_move(board, row, col, current_player):
# Check if the current player wins
winner = check_winner(board)
if winner != 0:
print("Player", winner, "wins!")
break
# Check if the game is a draw
if is_board_full(board):
print("It's a draw!")
break
# Switch to the next player
current_player = 2 if current_player == 1 else 1
else:
print("Invalid move. Try again.")
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]
[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]
28
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE 2023 - 2024
[1, 1, 1]
[1, 0, 2]
Player 1 wins!
Result:
Thus the Simulation of Game playing problem was written, executed and verified
successfully.
29